PHP strtotime() Function

It’s always a pain to deal with dates when coding. Most date-oriented functions expect UNIX timestamps, which is hardly a user-friendly format, and at a glance it’s near impossible to do something simple in theory, such as adding three days to a date. Generally the best strategy is to convert all dates into UNIX timestamp format, and then you can reformat it with date() when you want to display it in a human-readable format.

Fairly recently, when I was working on WP125, I came across a very useful function called strtotime(). It’s one of the coolest functions I’ve ever found in PHP. As the name suggests, it can convert a string into an equivalent timestamp.

Want to convert a date string into a UNIX timestamp? It’s as simple as the following, just note that there are some quirks. You must pass the string in a U.S. English format (month before the day, for example) and if you specify a string with a two-digit year in it, years before 1970 are mapped to 21st-century years instead of twentieth.

$timestamp = strtotime('April 1, 2009');
$timestamp = strtotime('next Saturday');
$timestamp = strtotime('07/05/2008');

Suppose you have a date, be it a timestamp or not, and you would like to add a certain amount of time to it. Maybe you would like to add three days to a date, or subtract month to a date.

$timestamp = strtotime('April 1, 2009 + 3 days');
$timestamp = strtotime('07/05/2008 - 1 month');

Isn’t that easy? It’s certainly simpler than the slightly convoluted method that I used in WP125, since I wasn’t aware of the easier alternative.

Strtotime() is a very useful function, and a quite advanced one as well. The range of inputs it can parse is quite large, and it really makes a developer’s work easier.

  • http:/// Dan Lee

    Its neat alright, but I have found issues with it in the past. I came across this bug. Be sure and read up on the comments at as they have found more, most of them revolving around time zones. It definitely has its uses, just be careful and know what is and isn’t bulletproof.

    Link to the bug I encountered:

  • Matt

    Well that certainly is a bad bug, Dan. I’ll have to read up on the functions…shortcomings, I guess.

  • Jon

    One of the most useful PHP functions for me. Also you can format the date like this:

    $newdate = date(‘Y-m-d’, strtotime($date.’+3 days’);

    Where $date is any string date.

  • Shofiqul Islam

    How I can get server current time integer format using strtotime() function