Ancient Temple City

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';
Labels:
Reactions:

Post a Comment

[blogger]

MKRdezign

{facebook#http://www.facebook.com/GTVCreations} {twitter#http://www.twitter.com/GTVCreations} {google-plus#http://www.google.com} {pinterest#http://www.pinterest.com} {youtube#http://www.youtube.com} {instagram#http://www.instagram.com}

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget