Skip to content

Instantly share code, notes, and snippets.

@mducharme
Created April 9, 2018 01:18
Show Gist options
  • Save mducharme/c0eeb615c0bf48d4ad05a518317e4141 to your computer and use it in GitHub Desktop.
Save mducharme/c0eeb615c0bf48d4ad05a518317e4141 to your computer and use it in GitHub Desktop.
DateTimeParser.php
@@ -0,0 +1,45 @@
<?php
namespace Charcoal\Model\Service;
use DateTime;
use DateTimeInterface;
use Exception;
use InvalidArgumentException;
/**
* Ensure a value is a DateTime (or null).
*/
class DateTimeParser
{
/**
* Ensure a variable is a proper DateTime (Interface). Also allows null value.
*
* @param DateTimeInterface|string|null $ts The timestamp value (datetime object, null or timestamp string) to parse.
* @throws InvalidArgumentException If the string parameter is an invalid time string, or the parameter is an invalid type.
* @return DateTimeInterface|null
*/
public function parse($ts)
{
if ($ts === null) {
return null;
}
if (is_string($ts)) {
try {
$ts = new DateTime($ts);
} catch (Exception $e) {
throw new InvalidArgumentException(
sprintf('Caould not parse date-time string: "%s"'),
$e->getMessage()
);
}
}
if (!($ts instanceof DateTimeInterface)) {
throw new InvalidArgumentException(
'Can not parse date-time. Must be a date-time object, null or a timestamp string.'
);
}
return $ts;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment