Friday, 23 August 2013

How to detect Ambiguous and Invalid DateTime in PHP?

How to detect Ambiguous and Invalid DateTime in PHP?

When dealing with local DateTime values provided by a user, it's quite
possible to have a time that is either invalid or ambiguous, due to
Daylight Saving Time transitions.
In other languages and frameworks, there are often methods such as
isAmbiguous and isValid, on some representation of the time zone. For
example in .NET, there is TimeZoneInfo.IsAmbiguousTime and
TimeZoneInfo.IsInvalidTime. Plenty of other time zone implementations have
similar methods.
PHP has excellent time zone support, but I can't seem to find these. The
closest thing I can find is DateTimeZone::getTransitions. That provides
the raw data, so I can see that some methods could be written on top of
this. But do they exist already somewhere? If not, can anyone provide a
good implementation? I would expect them to work something like this:
$tz = new DateTimeZone('America/New_York');
echo $tz-> isValidTime(new DateTime('2013-03-10 02:00:00')); # false
echo $tz-> isAmbiguousTime(new DateTime('2013-11-03 01:00:00')); # true

No comments:

Post a Comment