How to convert a string to a time with PHP

Josh Sherman
1 min read
Software Development 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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles