Aidan's PHP Repository

A repository for PHP functions and classes ...

function.convert_timestamp.php

Convert MySQL timestamp to unix timestamp

  • Author: Aidan Lister <aidan@php.net>
  • Version: 1.1.0
  • Link: http://aidanlister.com/repos/v/function.convert_timestamp.php
  • Views: 16641
  • Downloads: 1684

Source

Download this script <?php
/**
 * Convert MySQL timestamp to unix timestamp
 *
 * @author      Aidan Lister <aidan@php.net>
 * @version     1.1.0
 * @link        http://aidanlister.com/repos/v/function.convert_timestamp.php
 * @param       string      $timestamp      MySQL timestamp
 */
function convert_timestamp ($timestamp)
{
    $parts = sscanf($timestamp, '%04u%02u%02u%02u%02u%02u');
    $string = vsprintf('%04u-%02u-%02u %02u:%02u:%02u', $parts);
 
    return strtotime($string);
}
 
?>

Example

<pre>
<?php
require_once 'function.convert_timestamp.php';
 
// Get a MySQL timestamp
$result = mysql_query("SELECT NOW() + 0");
$datetime = mysql_result($result, 0);
echo "MySQL Datetime$datetime\n";
 
// Convert to unix timestamp
$timestamp = convert_timestamp($datetime);
echo "Unix Timestamp$timestamp\n";
 
// Better
$result = mysql_query("SELECT UNIX_TIMESTAMP(NOW())");
$datetime = mysql_result($result, 0);
echo "Unix Timestampfrom MySQL$datetime\n";
?>
</pre>

Output

MySQL Datetime: 20080725101026
Unix Timestamp: 1216944626
Unix Timestamp, from MySQL: 1216944626

Comments

December 1st, 2005
Perfect!!
April 21st, 2005
that proves that i should learn even more about MySQL that coding my ass off in php... thx for the UNIX_TIMESTAMP() tip...it's really nice and saves a lot of code...
December 3rd, 2004
good idea!
November 5th, 2004
Nice. Just what I wanted to do, but this way I don't have to think, heheh :-)
November 5th, 2004
Hehe, nice. Thx. :))