Convert a date to a UNIX timestamp with PHP

by Glyn Mooney

In this article I will cover how to convert a date from such things as a database like MySQL, RSS feed or other formats into a UNIX timestamp. Firstly for some people it will be handy to know what a UNIX timestamp actually is. A UNIX timestamp is the number of seconds that have passed since midnight on the 1st January, 1970 also known as the birth of modern computing.

In PHP there two; nice, simple functions for generating UNIX timestamps. The first is the “time()” function used as follows:

<?php
//Get the current UNIX timestamp
$now = time();
//Get the date one week from now as a UNIX timestamp
$nextweek = $now + (3600 * 24 * 7);
//Get the date last week as a UNIX timestamp
$nextweek = $now + (3600 * 24 * 7);
//Compare the dates
if ($lastweek < $nextweek) echo 'Next week is greater than last week';
?>

I think you can gather from that that UNIX timestamps are quite useful when you need to calculate or compare dates. Because a UNIX timestamp is in seconds it is treated like any other integer number.

Now for the function we would use to generate a UNIX timestamp from a date:

<?php
//The following date could be any date in
//ISO 8601, RFC 2822 and even non ISO
//or RFC standards
$date = date('Y-m-d h:i:s');
//Get the UNIX timestamp
$timestamp = strtotime($date);
?>

As you can see it’s really quite simple to get a UNIX timestamp from a date. But that’s not all you can do all sorts of amazing things with dates in PHP. To see more great examples of just how flexible the strtotime function really is just look at the PHP function reference at http://php.net/manual/en/function.strtotime.php.

Hope this helps.