Skip to content

Instantly share code, notes, and snippets.

@cyberwani
Forked from dnaber-de/datetime-iso-to-mysql
Last active December 10, 2015 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyberwani/4396301 to your computer and use it in GitHub Desktop.
Save cyberwani/4396301 to your computer and use it in GitHub Desktop.
<?php
/**
* datetime_iso_to_mysql
*
* if the iso string comes without timezone information
* we gues it's utc and append this to leave no doubt
* remeber to set your systems default timezone with
* date_default_timezone_set()
*
* @param string $iso an ISO Formated datetime string
* @return array $mysql_date keys are local and utc
*/
function datetime_iso_to_mysql( $iso ) {
$iso = trim( $iso );
if ( empty( $iso ) ) {
return;
}
if ( ! preg_match( '#(?:[+-]\d\d(?::\d\d)?)|Z$#', $iso ) ) {
$iso .= 'Z';
}
$mysql_date = array();
$ts = strtotime( $iso );
$mysql_date[ 'utc' ] = date( 'Y-m-d H:i:s', $ts );
$local = localtime( $ts, TRUE );
$t = array();
$t[ 'Y' ] = $local[ 'tm_year' ] + 1900;
$t[ 'm' ] = $local[ 'tm_mon' ] + 1;
$t[ 'd' ] = $local[ 'tm_mday' ];
$t[ 'H' ] = $local[ 'tm_hour' ];
$t[ 'i' ] = $local[ 'tm_min' ];
$t[ 's' ] = $local[ 'tm_sec' ];
foreach( $t as $k => &$v ) {
if ( 'Y' == $k )
continue;
if ( 1 == strlen( $v ) )
$v = '0' . $v;
}
extract( $t );
$mysql_date[ 'local'] = $Y . '-' . $m . '-' . $d . ' ' . $H . ':' . $i . ':' . $s;
return $mysql_date;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment