How to convert a string to a time with PHP

Converting a string to a timestamp is one of my favorite things about PHP. In
fact when trying to decide which language to build [HolidayAPI][holidayapi] in
I couldn’t find an implementation of PHP’s strtotime() that rivaled the
original. The strtotime() function takes a textual string as input and then
spits back a timestamp, which can then be used to generate a more human
readable date time string.

Here are some examples of how you can use strtotime() to find out the date
and time of relative strings:

strtotime('tomorrow'
strtotime('next Tuesday'
strtotime('3rd Thursday of Februrary'
strtotime('+90 days'
strtotime('July 4th, 2015 +2 weeks'

Not ever string works but quite a few do. Also the resulting timestamp is based
on the current day unless you explicitly tell it a date, like my last example.

I recently found out about an interval that I didn’t realized worked. It’s the
weekday keyword. Would come in handy when you need to calculate business
days for say, shipping or something.

strtotime('today +7 weekdays'

As mentioned, this returns the UNIX timestamp but you can easily convert it to
something more friendly with the date() function.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.