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.