Created
July 19, 2012 00:26
-
-
Save hobodave/3139928 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace My\Util; | |
define('MYSQL_ZERO_DATE', '0000-00-00'); | |
define('MYSQL_ZERO_DATETIME', '0000-00-00 00:00:00'); | |
define('MYSQL_ZERO_DATETIME_INT64', -62169962400); // This is clearly flawed since it is time-zone dependent. | |
class Time | |
{ | |
/** | |
* Simple function to 'scrub' passed in time into a specific format. | |
* | |
* @param mixed $date | |
* @param string $format | |
* @param string $empty | |
* @return string | |
*/ | |
public static function formatDate($date, $format = MYSQL_FORMAT_DATE, $empty = MYSQL_ZERO_DATE) | |
{ | |
if ($date === MYSQL_ZERO_DATE | |
|| $date === MYSQL_ZERO_DATETIME | |
|| $date === MYSQL_ZERO_DATETIME_INT64 | |
|| (empty($date) && $date !== 0) | |
) { | |
return $empty; | |
} | |
$dt = new DateTime(); | |
try { | |
if (is_integer($date)) { | |
$dt->setTimestamp($date); | |
} else { | |
$dt->modify($date); | |
} | |
} catch (Exception $e) { | |
return $empty; | |
} | |
$errors = DateTime::getLastErrors(); | |
if ($errors['warning_count'] + $errors['error_count'] > 0) { | |
return $empty; | |
} | |
return $dt->format($format); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment