Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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," ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page