Convert Time Into Timestamp Or Timestamp Into Time In PHP

The easiest (and most reliable) way to store the time in a database table is with a timestamp. It is also the most convenient way of working out time scales as you don't have to do calculations in base 60. In MySQL this is accomplished by the UNIXTIME() function, which can be reversed by using another MySQL function called FROM_UNIXTIME().

However, you can sometimes be left with timestamps in your code and the task of trying to figure out what to do with them.

The first problem is trying to convert a timestamp into a date. So here is a PHP function that does this.

function timestamp($t = null){
 if($t == null){
  $t = time();
 return date('Y-m-d H:i:s', $t);

And if you ever have a the opposite problem then here is a PHP function that converts a date string into a timestamp. At the moment the string needs to be in the format YYYY-MM-DD HH:MM:SS, which is what the previous function produced. This isn't too difficult to change, just alter the parameters and order of the explode(' ', $str).

function convert_datetime($str) {
 list($date, $time) = explode(' ', $str);
 list($year, $month, $day) = explode('-', $date);
 list($hour, $minute, $second) = explode(':', $time);
 $timestamp = mktime($hour, $minute, $second, $month, $day, $year);
 return $timestamp;

Here is an example of the functions in use.

echo timestamp(convert_datetime('2008-05-10 20:56:00')). '  '. convert_datetime('2008-05-10 20:56:00') . ' 1210467360';

Add new comment

The content of this field is kept private and will not be shown publicly.
1 + 6 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.