PHP Date / Time Function: strtotime

PHP has number of date and time functions. One is date(), which I feel, is most used date and time function. Time() function can be another most used time function. But the most interesting date and time function I feel is the function strtotime(). It is interesting as it understand the human language. It can give you the UNIX timestamps from the text like "next", "now", "+1 day", "next monday", etc. Is not this interesting? Once it returned a Unix timestamps, we can convert it to desired date-time format using date() function.

echo date('y-m-d h:i:s', strtotime('next'));

echo date('y-m-d h:i:s', strtotime('now'));

echo date('y-m-d h:i:s', strtotime('+1 day'));

echo date('y-m-d h:i:s', strtotime('next Monday'));

// Suppose we got timestamp from somewhere for 10 Jan 2010 and we want the date of Monday just after that

$timestamp = strtotime('10 January, 2010');

echo date('y-m-d h:i:s', strtotime('next Monday', $timestamp)); // 11 Jan ?

// RFC822 formatted date, 5 months in advance
// will output in format: Mon, 14 Feb 11 23:14:31 +0530
echo date(DATE_RFC822, strtotime('+5 months'));

Important: On failure strtotime() returns -1 (minus 1) prior to 5.1.0, and FALSE from version 5.1.0. It is a big change. It may be affected many application.

Important: PHP function - strtotime() accepts variety of string representations for date and time, but it expect you to give US English date format. Otherwise it can fail.

echo strtotime('10-09-2010'); // works

echo strtotime('10092010'); // not works

echo strtotime('2010-09-10'); // works

echo strtotime('20100910'); // works

This function is also very handy in date and time comparison. Just provide date-time to strtotime and it will convert it into Unix date-time. Now it is simple difference (datetime1 - datetime2). A new function has come for date-time difference - date_diff() in PHP  version 5.2.0.

Comments are open for an year period. Please, write here on Facebook page.