Skip to content

Instantly share code, notes, and snippets.

@fragoulis
Last active August 29, 2015 14:07
Show Gist options
  • Save fragoulis/d2be339a04fbba676cf8 to your computer and use it in GitHub Desktop.
Save fragoulis/d2be339a04fbba676cf8 to your computer and use it in GitHub Desktop.
Get current datetime with timezone and microsecond precision
<?php
/**
* Generate datetime with timezone support and microsend precision.
*
* Example:
* ```
* $now = Datetime::now(); // generates YYYY-MM-DDTHH:MM:SS.MMMMMM
* ```
*
* @author John Fragkoulis <john.fragkoulis@gmail.com>
**/
class Datetime
{
public static $defaultTimezone = 'Europe/Athens';
public static $defaultFormat = 'Y-m-d\TH:i:s.u';
public static function now($format=null, $timezone=null)
{
$format = $format ? $format : static::$defaultFormat;
$timezone = $timezone ? $timezone : static::$defaultTimezone;
$datetime = date_create_from_format('U.u', microtime(true));
$datetime->setTimezone(new DateTimeZone($timezone));
return $datetime->format($format);
}
}
@fragoulis
Copy link
Author

Supported by PHP 5.3 or greater

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment