| 1 | <?php |
||
| 10 | trait DateTimeHelper |
||
| 11 | { |
||
| 12 | /** |
||
| 13 | * Create DateTime object from time string and timezone. |
||
| 14 | * |
||
| 15 | * @param null|string $time Time string, default to 'now' |
||
| 16 | * @param null|string $tz Timezone, default if omitted |
||
| 17 | * |
||
| 18 | * @throws \RuntimeException |
||
| 19 | * |
||
| 20 | * @return \DateTimeImmutable |
||
| 21 | */ |
||
| 22 | 15 | private static function _createDateTime( |
|
| 23 | ?string $time = null, ?string $tz = null): \DateTimeImmutable |
||
| 24 | { |
||
| 25 | 15 | if (!isset($time)) { |
|
| 26 | 4 | $time = 'now'; |
|
| 27 | } |
||
| 28 | 15 | if (!isset($tz)) { |
|
| 29 | 11 | $tz = date_default_timezone_get(); |
|
| 30 | } |
||
| 31 | try { |
||
| 32 | 15 | $dt = new \DateTimeImmutable($time, self::_createTimeZone($tz)); |
|
| 33 | 13 | return self::_roundDownFractionalSeconds($dt); |
|
| 34 | 2 | } catch (\Exception $e) { |
|
| 35 | 2 | throw new \RuntimeException( |
|
| 36 | 'Failed to create DateTime: ' . |
||
| 37 | 2 | self::_getLastDateTimeImmutableErrorsStr(), 0, $e); |
|
| 38 | } |
||
| 39 | } |
||
| 40 | |||
| 41 | /** |
||
| 42 | * Rounds a \DateTimeImmutable value such that fractional |
||
| 43 | * seconds are removed. |
||
| 44 | * |
||
| 45 | * @param \DateTimeImmutable $dt |
||
| 46 | * |
||
| 47 | * @return \DateTimeImmutable |
||
| 48 | */ |
||
| 49 | 14 | private static function _roundDownFractionalSeconds( |
|
| 50 | \DateTimeImmutable $dt): \DateTimeImmutable |
||
| 51 | { |
||
| 52 | 14 | return \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', |
|
|
1 ignored issue
–
show
|
|||
| 53 | 14 | $dt->format('Y-m-d H:i:s'), $dt->getTimezone()); |
|
| 54 | } |
||
| 55 | |||
| 56 | /** |
||
| 57 | * Create DateTimeZone object from string. |
||
| 58 | * |
||
| 59 | * @param string $tz |
||
| 60 | * |
||
| 61 | * @throws \UnexpectedValueException |
||
| 62 | * |
||
| 63 | * @return \DateTimeZone |
||
| 64 | */ |
||
| 65 | 15 | private static function _createTimeZone(string $tz): \DateTimeZone |
|
| 71 | } |
||
| 72 | } |
||
| 73 | |||
| 74 | /** |
||
| 75 | * Get last error caused by DateTimeImmutable. |
||
| 76 | * |
||
| 77 | * @return string |
||
| 78 | */ |
||
| 85 |