Skip to content

Instantly share code, notes, and snippets.

@AllenJB
Created September 23, 2022 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AllenJB/689299e5481cb74905e17ca2e91cffce to your computer and use it in GitHub Desktop.
Save AllenJB/689299e5481cb74905e17ca2e91cffce to your computer and use it in GitHub Desktop.
PHP DateTimeFactory
<?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