ArrayUtil.php
1 year ago
DefaultLogger.php
1 year ago
JsonSerializable.php
1 year ago
Logger.php
1 year ago
StringUtil.php
1 year ago
TimeUnit.php
1 year ago
TimeUtil.php
1 year ago
TimeValue.php
1 year ago
UrlUtil.php
1 year ago
TimeUtil.php
55 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WonderPush\Util; |
| 4 | |
| 5 | if (count(get_included_files()) === 1) { http_response_code(403); exit(); } // Prevent direct access |
| 6 | |
| 7 | /** |
| 8 | * Utility class for time manipulation. |
| 9 | */ |
| 10 | class TimeUtil { |
| 11 | |
| 12 | /** |
| 13 | * Parse an ISO 8601 date with optional time into a `\DateTime`. |
| 14 | * @param string $str |
| 15 | * @return \DateTime|null |
| 16 | */ |
| 17 | public static function parseISO8601DateOptionalTime($str) { |
| 18 | // Parse parts |
| 19 | $rtn = preg_match('/^(\d\d\d\d(?:-\d\d(?:-\d\d)?)?)(?:T(\d\d(?::\d\d(?::\d\d(?:.\d\d\d)?)?)?))?(Z|[+-]\d\d(?::\d\d(?::\d\d(?:.\d\d\d)?)?)?)?$/', $str, $matches); |
| 20 | if ($rtn !== 1) { |
| 21 | return null; |
| 22 | } |
| 23 | $date = $matches[1]; |
| 24 | $time = ArrayUtil::getIfSet($matches, 2, ''); |
| 25 | $offset = ArrayUtil::getIfSet($matches, 3, ''); |
| 26 | // Fill parts to default unspecified items |
| 27 | $date .= substr('1970-01-01', strlen($date)); |
| 28 | $time .= substr('00:00:00.000000', strlen($time)); |
| 29 | if ($offset === 'Z') $offset = ''; |
| 30 | $offset .= substr('+00:00', strlen($offset)); |
| 31 | $offset = substr($offset, 0, 6); // second.milliseconds are not supported by the parser |
| 32 | // Create fully specified date |
| 33 | $str = $date . 'T' . $time . $offset; |
| 34 | // Parse the date |
| 35 | $parsed = \DateTime::createFromFormat('Y-m-d\TH:i:s.uP', $str); |
| 36 | if ($parsed === false) { |
| 37 | $parsed = null; |
| 38 | } |
| 39 | return $parsed; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Converts a `\DateTime` into a unix timestamp in milliseconds. |
| 44 | * @param \DateTime $dt |
| 45 | * @return integer|null |
| 46 | */ |
| 47 | public static function getMillisecondTimestampFromDateTime($dt) { |
| 48 | if (!($dt instanceof \DateTime)) { |
| 49 | return null; |
| 50 | } |
| 51 | return $dt->getTimestamp() * 1000 + round((int)$dt->format('u') / 1000); |
| 52 | } |
| 53 | |
| 54 | } |
| 55 |