Programster's Blog

Tutorials focusing on Linux, programming, and open-source

PHP Time/Date Cheatsheet

PHP

Converting User Input

$timestamp = strtotime("01/01/1999");
$timestamp = strtotime(915148800);
$timestamp = strtotime("1st January 1999");

You now have the unix timestamp (number of seconds as an integer, since 1st January 1970)

PHP considers date strings with - to be English, and dates with / to be American.

# This is the the 2nd of Jan, not the 1st of Feb
$timestamp = strtotime("01/02/1999");

# This is the the 1st of Feb, not the 2nd of Jan
$timestamp = strtotime("01-02-1999");

Since the timestamp is just an integer, you can print it or perform maths with it.

print $timestamp; // outputs 915148800

# one day later
$dayLater = $timestamp + (60 * 60 * 24);

Converting To Human Form

Use the date() function to output in a human readable form. E.g.

// outputs Friday 1st January 1999
echo date('l jS F Y', $timestamp); 

// outputs 01-02-1999 (british)
echo date('d-m-Y', $timestamp);

// outputs 02/01/1999 (americans)
echo date('m/d/Y', $timestamp);

// The format for 23:01:01 would be:
echo date('H:i:s', $timestamp);

// For 12 hour fomat with leading 0s:
echo date('h:i:s', $timestamp);

Be careful not to do this:

$timestamp = strtotime("2nd January 1999");
$humanTime = date('d/m/Y', $timestamp);
$newTimestamp = strtotime($humanTime);
// $timestamp !== $newTimestamp

Misc

Convert Time to Seconds

If you want to know how many seconds a time like 36 minutes past 9 AM is in seconds since midnight execute the following:

echo strtotime('09:36') - strtotime('TODAY');

This is also the same as:

echo strtotime('09:36:00') - strtotime('TODAY');

Getting Current MySQL Timestamp String

If you want to create the timstamp string and insert it rather than rely on MySQL creating the timestamp for you, then you can use this:

echo date('Y-m-d H:i:s', time());

References