Name

strtotime()

Synopsis

    int strtotime ( string time [, int now] )

The strtotime() function converts strings to a timestamp and takes two parameters: the string time to convert, and a second optional parameter that can be a relative timestamp. Parameter one is important; we will come back to parameter two shortly. Consider this script:

    print strtotime("22nd December 1979");
    print strtotime("22 Dec. 1979 17:30");
    print strtotime("1979/12/22");

Here, there are three ways of representing the same date with the second also including a time. If you run that script, you will see PHP output an integer for each one, with the first and third being the same, and the second one being slightly higher. These numbers are the Unix timestamps for the dates we passed into strtotime(), so it successfully managed to convert them.

You must use American-style dates (i.e., month, day, year) with strtotime(); if it finds a date like 10/11/2003, it will consider it to be October 11th as opposed to November 10th.

If PHP is unable to convert your string into a timestamp, it will return -1. This next example tests whether date conversion worked or not:

    $mydate = strtotime("Christmas 1979");
    if ($mydate == -1) {
            print "Date conversion failed!";
    } else {
            print "Date conversion succeeded!";
    }

The strtotime() function has an optional second parameter, which is a timestamp to use for relative dates. This is because the date string in the first parameter to strtotime() can include relative dates such as "Next Sunday," ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.