Home » Database » MySQL » PHP Date or Datetime to MySQL Datetime and viceversa

PHP Date or Datetime to MySQL Datetime and viceversa

Two useful PHP functions to convert normal date/datetime (“25.12.2010 12:10:00” or “25.12.2010”) to MySQL datetime (like “2010-12-25 12:10:00” or “2010-12-25 00:00:00″); You can get back a date/datetime from MySQL datetime too:

[sourcecode language=”php”] function datetime2mysqldatetime($datetime){ // ‘25.12.2010 12:10:00’ -> ‘2010-12-25 12:10:00’
return date(‘Y-m-d H:i:s’, strtotime($datetime)); // ‘25.12.2010’ -> ‘2010-12-25 00:00:00’
}

function mysqldatetime2datetime($mysql_datetime){ // ‘2010-12-25 12:10:00’ -> ‘25.12.2010 12:10:00’
$d = split(‘ ‘, $mysql_datetime); // ‘2010-12-25’ -> ‘25.12.2010’
if($d && count($d)>1){
list($year, $month, $day) = split(‘-‘, $d[0]);
list($hour, $minute, $second) = split(‘:’, $d[1]);
$d = date(‘d.m.Y H:i:s’, mktime($hour, $minute, $second, $month, $day, $year));}
else if($d && count($d)==1){
list($year, $month, $day) = split(‘-‘, $d[0]);
$d = date(‘d.m.Y’, mktime(0, 0, 0, $month, $day, $year));
} else {
$d = NULL;
}
return $d;
}
[/sourcecode]

Max 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.