Created
September 23, 2022 18:08
-
-
Save AllenJB/689299e5481cb74905e17ca2e91cffce to your computer and use it in GitHub Desktop.
PHP DateTimeFactory
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 | |
class DateTimeFactory | |
{ | |
public static function createImmutableFromFormat(string $format, string $time, \DateTimeZone $timezone = null) : \DateTimeImmutable | |
{ | |
$dt = \DateTimeImmutable::createFromFormat($format, $time, $timezone); | |
// DateTime errors/warnings can occur even if the object was successfully created (eg. invalid date) | |
$errors = \DateTimeImmutable::getLastErrors(); | |
if (count($errors['errors'] ?? []) > 0) { | |
/** @noinspection LoopWhichDoesNotLoopInspection */ | |
foreach ($errors['errors'] as $pos => $msg) { | |
throw new \InvalidArgumentException($msg . ' @ character ' . $pos); | |
} | |
} | |
if (count($errors['warnings'] ?? []) > 0) { | |
/** @noinspection LoopWhichDoesNotLoopInspection */ | |
foreach ($errors['warnings'] as $pos => $msg) { | |
throw new \InvalidArgumentException($msg . ' @ character ' . $pos); | |
} | |
} | |
if (! ($dt instanceof \DateTimeImmutable)) { | |
throw new \InvalidArgumentException("Invalid DateTime value specified"); | |
} | |
return $dt; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment