Skip to content

Instantly share code, notes, and snippets.

@mikelbring
Forked from ellisio/gist:2364069
Created April 12, 2012 01:18
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 mikelbring/2364079 to your computer and use it in GitHub Desktop.
Save mikelbring/2364079 to your computer and use it in GitHub Desktop.
<?php
class Date {
/**
* Convert a local timestamp to a GMT timestamp.
*
* @static
*
* @param string $timestamp
* @param string $timezone
* @param string $format
*
* @return string
*/
public static function local_to_gmt($timestamp, $timezone, $format = '')
{
if ($format == '')
{
$format = self::FORMAT_SQL;
}
if (is_numeric($timezone))
{
$dt = new DateTime($timestamp);
$timestamp = intval($dt->format('U')) - (floatval($timezone) * 60 * 60);
return date($format, $timestamp);
}
else
{
$dt = new DateTime($timestamp, new DateTimeZone($timezone));
$dt->setTimezone(new DateTimeZone('GMT'));
return $dt->format($format);
}
}
/**
* Converts a GMT timestamp to the local timestamp.
*
* @static
*
* @param string $timestamp
* @param string $timezone
* @param string $format
*
* @return string
*/
public static function gmt_to_local($timestamp, $timezone, $format = '')
{
if ($format == '')
{
$format = self::FORMAT_DISPLAY;
}
try
{
$dt = new DateTime($timestamp, new DateTimeZone('GMT'));
$dt->setTimezone(new DateTimeZone($timezone));
return $dt->format($format);
} catch (Exception $e)
{
return date($format, $timestamp); // Just send back what we get.
}
}
/**
* Get all the dateparts for the local time.
*
* @static
*
* @param string $timestamp
* @param string $timezone
*
* @return array
*/
public static function gmt_to_local_dateparts($timestamp, $timezone)
{
$dt = new DateTime($timestamp, new DateTimeZone('GMT'));
try
{
$dt->setTimezone(new DateTimeZone($timezone));
} catch (Exception $e)
{
$dt->setTimezone(new DateTimeZone('US/Eastern'));
}
return array(
$dt->format('U'),
'seconds' => intval($dt->format('s')),
'minutes' => intval($dt->format('i')),
'hours' => $dt->format('G'),
'mday' => $dt->format('j'),
'wday' => $dt->format('w'),
'mon' => $dt->format('n'),
'year' => $dt->format('Y'),
'yday' => $dt->format('z'),
'weekday' => $dt->format('l'),
'month' => $dt->format('F'),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment