How to detect Ambiguous and Invalid DateTime in PHP? - 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, or functionality to address this concern. For example, in Python, the pytz library will throw an AmbiguousTimeError or InvalidTimeError exception that you can trap.
PHP has excellent time zone support, but I can't seem to find anything to address this. 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

I 'm not aware of any existing implementations and I haven't had cause to use advanced date/time features such as these as yet, so here is a clean room implementation.
To enable the syntax illustrated in the question we are going to extend DateTimeZone as follows:
class DateTimeZoneEx extends DateTimeZone
{
const MAX_DST_SHIFT = 7200; // let's be generous
// DateTime instead of DateTimeInterface for PHP < 5.5
public function isValidTime(DateTimeInterface $date);
public function isAmbiguousTime(DateTimeInterface $date);
}
To keep distracting details from cluttering the implementation, I am going to assume that the $date arguments have been created with the proper time zone; this is in contrast to the example code given in the question.
That is to say, the correct result will not be produced by this:
$tz = new DateTimeZoneEx('America/New_York');
echo $tz->isValidTime(new DateTime('2013-03-10 02:00:00'));
but instead by this:
$tz = new DateTimeZoneEx('America/New_York');
echo $tz->isValidTime(new DateTime('2013-03-10 02:00:00', $tz));
Of course since $tz is already known to the object as $this, it should be easy to extend the methods so that this requirement is removed. In any case, making the interface super user friendly is out of the scope of this answer; going forward I will focus on the technical details.
isValidTime
The idea here is to use getTransitions to see if there are any transitions around the date/time we are interested in. getTransitions will return an array with either one or two elements; the timezone situation for the "begin" timestamp will always be there, and another element will exist if a transition occurs shortly after it. The value of MAX_DST_SHIFT is small enough that there is no chance of getting a second transition/third element.
Let's see the code:
public function isValidTime(DateTime $date)
{
$ts = $date->getTimestamp();
$transitions = $this->getTransitions(
$ts - self::MAX_DST_SHIFT,
$ts + self::MAX_DST_SHIFT
);
if (count($transitions) == 1) {
// No DST changes around here, so obviously $date is valid
return true;
}
$shift = $transitions[1]['offset'] - $transitions[0]['offset'];
if ($shift < 0) {
// The clock moved backward, so obviously $date is valid
// (although it might be ambiguous)
return true;
}
$compare = new DateTime($date->format('Y-m-d H:i:s'), $this);
return $compare->modify("$shift seconds")->getTimestamp() != $ts;
}
The final point of the code depends on the fact that PHP's date functions calculate timestamps for invalid date/times as if wall clock time had not shifted. That is, the timestamps calculated for 2013-03-10 02:30:00 and 2013-03-10 03:30:00 will be identical on the New York timezone.
It's not difficult to see how to take advantage of this fact: create a new DateTime instance equal to the input $date, then shift it forward in wall clock time terms an amount equal to the DST shift in seconds (it is imperative that DST not be taken into account to make this adjustment). If the timestamp of the result (here the DST rules come into play) is equal to the timestamp of the input, then the input is an invalid date/time.
isAmbiguousTime
The implementation is quite similar to isValidTime, only a few details change:
public function isAmbiguousTime(DateTime $date)
{
$ts = $date->getTimestamp();
$transitions = $this->getTransitions(
$ts - self::MAX_DST_SHIFT,
$ts + self::MAX_DST_SHIFT);
if (count($transitions) == 1) {
return false;
}
$shift = $transitions[1]['offset'] - $transitions[0]['offset'];
if ($shift > 0) {
// The clock moved forward, so obviously $date is not ambiguous
// (although it might be invalid)
return false;
}
$shift = -$shift;
$compare = new DateTime($date->format('Y-m-d H:i:s'), $this);
return $compare->modify("$shift seconds")->getTimestamp() - $ts > $shift;
}
The final point depends on another implementation detail of PHP's date functions: when asked to produce the timestamp for an ambiguous date/time, PHP produces the timestamp of the first (in absolute time terms) occurrence. This means that the timestamps of the latest ambiguous time and the earliest non-ambiguous time for a given DST change will differ by an amount larger than the DST offset (specifically, the difference will be in the range [offset + 1, 2 * offset], where offset is an absolute value).
The implementation takes advantage of this by again doing a "wall clock shift" forward and checking the timestamp difference between the result and the input $date.
See the code in action.

Related

How can I create a relative PHP DateTime for the next instance of a particular time?

So it seems like the PHP DateTime class allows you to use simple relative language strings such a next Monday 12:00 to create objects associated with relative dates.
The Problem
The use case I'd like to achieve is to omit the day ("Monday") from the above string, and create a DateTime object for the next instance of 06:00.
This presents a challenge because the code may be running at 07:00, in which case the string 06:00 will return a date which is in the past, whereas if we run the code at 05:00 (or anytime before 06:00), we will get the correct result.
Note: As an addendum, I don't want to have to do a bunch of complicated arithmetic and want to leverage the DateTime class to its fullest to keep myself from any sneaky little TimeZone or leap year issues.
My Question
How can I use the PHP DateTime class to obtain a DateTime object for the next instance of a certain time (without supplying the day as well)?
I created a PHP extension for the DateTime API called dt. You can find it here. Using it for this task is very simple. Some Examples:
$dt = dt::create("today 06:00");
if($dt->isPast()) {
$dt->modify("+ 1Day");
}
echo $dt;
Optionally, you can always set a time zone as the second parameter.
$time = "06:00";
$dt = dt::create("today $time","Africa/Johannesburg");
//:
The class works with special chains which can contain conditions. This allows you to create an expression that does the job with the create method alone.
$dt = dt::create("today 6:00|{{?YmdHis<NOW}}+1 Day");
The class also works with cron expressions.
$cron = "0 6 * * 1-5";//every Mo-Fr at 6:00
$dt = dt::create('now')->nextCron($cron);
Always delivers the next time 6:00 for Monday to Friday. At the weekend, the next time is Monday 6:00.
The Solution
Here's how I ended up solving this...
/*
* Simple function that returns a DateTime object representing the next instance of the time
* supplied by the $timeString parameter.
*
* $timeString: A string representing the time you wish to process, in 24h notation (i.e.
* '06:00' for 6:00am).
*/
function getNextTimeInstance($timeString){
// First, grab an instance of the current moment as a DateTime object ('now' is optional).
$rightNow = new DateTime('now');
// Basic initializations for the object we want to use.
$processedTime = new DateTime();
// Change the Timezone if you need to do so.
$processedTime->setTimezone(new DateTimeZone('Africa/Johannesburg'));
// Set the time for our working DateTime to the time we want (i.e. '06:00').
$processedTime->modify($timeString);
// If the next instance of this time we're trying to process is in the past
// (meaning it is "less than" the current moment).
if($rightNow > $processedTime){
// Simply add one day to our working DateTime object.
$processedTime->modify('+1 day');
}
// Return the DateTime objects that represents the next instance of that time.
return $processedTime;
}
I relied heavily on the following documentation to reach this result:
The PHP DateTime class.
The list of date formats that the PHP DateTime class will accept as inputs.
The list of supported TimeZone strings that PHP will accept.
I hope this helps anyone else stuck in the same situation as myself, and if anyone else has a more elegant solution, please feel free to contribute.

How can I check if a datetime is valid in PHP as per time jumps that occur for daylight savings time? [duplicate]

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, or functionality to address this concern. For example, in Python, the pytz library will throw an AmbiguousTimeError or InvalidTimeError exception that you can trap.
PHP has excellent time zone support, but I can't seem to find anything to address this. 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
I 'm not aware of any existing implementations and I haven't had cause to use advanced date/time features such as these as yet, so here is a clean room implementation.
To enable the syntax illustrated in the question we are going to extend DateTimeZone as follows:
class DateTimeZoneEx extends DateTimeZone
{
const MAX_DST_SHIFT = 7200; // let's be generous
// DateTime instead of DateTimeInterface for PHP < 5.5
public function isValidTime(DateTimeInterface $date);
public function isAmbiguousTime(DateTimeInterface $date);
}
To keep distracting details from cluttering the implementation, I am going to assume that the $date arguments have been created with the proper time zone; this is in contrast to the example code given in the question.
That is to say, the correct result will not be produced by this:
$tz = new DateTimeZoneEx('America/New_York');
echo $tz->isValidTime(new DateTime('2013-03-10 02:00:00'));
but instead by this:
$tz = new DateTimeZoneEx('America/New_York');
echo $tz->isValidTime(new DateTime('2013-03-10 02:00:00', $tz));
Of course since $tz is already known to the object as $this, it should be easy to extend the methods so that this requirement is removed. In any case, making the interface super user friendly is out of the scope of this answer; going forward I will focus on the technical details.
isValidTime
The idea here is to use getTransitions to see if there are any transitions around the date/time we are interested in. getTransitions will return an array with either one or two elements; the timezone situation for the "begin" timestamp will always be there, and another element will exist if a transition occurs shortly after it. The value of MAX_DST_SHIFT is small enough that there is no chance of getting a second transition/third element.
Let's see the code:
public function isValidTime(DateTime $date)
{
$ts = $date->getTimestamp();
$transitions = $this->getTransitions(
$ts - self::MAX_DST_SHIFT,
$ts + self::MAX_DST_SHIFT
);
if (count($transitions) == 1) {
// No DST changes around here, so obviously $date is valid
return true;
}
$shift = $transitions[1]['offset'] - $transitions[0]['offset'];
if ($shift < 0) {
// The clock moved backward, so obviously $date is valid
// (although it might be ambiguous)
return true;
}
$compare = new DateTime($date->format('Y-m-d H:i:s'), $this);
return $compare->modify("$shift seconds")->getTimestamp() != $ts;
}
The final point of the code depends on the fact that PHP's date functions calculate timestamps for invalid date/times as if wall clock time had not shifted. That is, the timestamps calculated for 2013-03-10 02:30:00 and 2013-03-10 03:30:00 will be identical on the New York timezone.
It's not difficult to see how to take advantage of this fact: create a new DateTime instance equal to the input $date, then shift it forward in wall clock time terms an amount equal to the DST shift in seconds (it is imperative that DST not be taken into account to make this adjustment). If the timestamp of the result (here the DST rules come into play) is equal to the timestamp of the input, then the input is an invalid date/time.
isAmbiguousTime
The implementation is quite similar to isValidTime, only a few details change:
public function isAmbiguousTime(DateTime $date)
{
$ts = $date->getTimestamp();
$transitions = $this->getTransitions(
$ts - self::MAX_DST_SHIFT,
$ts + self::MAX_DST_SHIFT);
if (count($transitions) == 1) {
return false;
}
$shift = $transitions[1]['offset'] - $transitions[0]['offset'];
if ($shift > 0) {
// The clock moved forward, so obviously $date is not ambiguous
// (although it might be invalid)
return false;
}
$shift = -$shift;
$compare = new DateTime($date->format('Y-m-d H:i:s'), $this);
return $compare->modify("$shift seconds")->getTimestamp() - $ts > $shift;
}
The final point depends on another implementation detail of PHP's date functions: when asked to produce the timestamp for an ambiguous date/time, PHP produces the timestamp of the first (in absolute time terms) occurrence. This means that the timestamps of the latest ambiguous time and the earliest non-ambiguous time for a given DST change will differ by an amount larger than the DST offset (specifically, the difference will be in the range [offset + 1, 2 * offset], where offset is an absolute value).
The implementation takes advantage of this by again doing a "wall clock shift" forward and checking the timestamp difference between the result and the input $date.
See the code in action.

how to convert PHP timezone string(e.g Europe/Berlin) to codeigniter timezone(e.g. UP1)

In a short if i have to ask this question is just the vice verse of this link question .
I am using a javscript library which automcatically detects the timezone and returns the time zone name in PHP format i.e 'Europe/Berlin' format.
But I make use of Codeigniters timezone_menu which gives a drop down box of time timezones and I am wondering how can i convert this php time zone (i.e 'Europe/Berlin' ) to codeigniters timezone format i.e UP1.?
It appears from the CodeIgniter documentation that they are treating time zones as fixed offsets. Their convention is fairly straight forward:
UTC to represent exactly UTC.
or
U to represent UTC
M or P for Minus or Plus
A number to describe the offset
A single digit for whole hour offsets
Two digits when there are half-hour offsets, but these are shifted funky (you would think +05:30 would be represented by UP55, but its actually UP45
So why did they do this? Who knows. It's not a standard thing, it's a CodeIgnitor special format. Normally an offset is just represented like +05:30 or +0530.
Using an offset to represent a whole time zone is out of sync with reality. If it was that easy, then we wouldn't need the IANA time zones like Europe/Berlin in the first place. You can see in the time zone list here that Europe/Berlin alternates between +01:00 and +02:00. Code Ignitor might say that it is UP1, but then that wouldn't ever take into account the daylight time offset. (Daylight saving time is different all over the world, so you can't just augment this with a checkbox and expect to be reliable.)
So, if you must have CodeIgnitor's strange form of time zone representation, then take the base offset of the IANA zone and apply their funky formula (as dev-null-dweller showed in his answer). Just don't expect it to be accurate.
And if you're in zone with a :45 offset, then you're out of luck. That would be Pacific/Chatham or Asia/Kathmandu.
You can read more in the timezone tag wiki under "Time Zone != Offset"
Just to add something actually constructive to to this answer, I recommend not using CodeIgnitor's time zones. Just stick with the IANA zones as provided for you by PHP. They are even kept up to date via timezondb in the PECL.
I don't know CI that much, but from quick look at the date helper documentation, it looks like it can be created from offset:
$now = new DateTime('now', new DateTimeZone('UTC'));
$tz = new DateTimeZone('America/Argentina/Buenos_Aires');
$offset = $tz->getOffset($now) / 3600;
$ci_tz = 'U';
if($offset) {
if($offset < 0) {
$ci_tz .= 'M';
$offset = abs($offset);
} else {
$ci_tz .= 'P';
}
if(is_float($offset)) {
$offset = $offset * 10 - 10;
}
$ci_tz .= (string)$offset;
} else {
$ci_tz .= 'TC';
}
var_dump($ci_tz); // UM3 = UTC Minus 3 hours

assistance with a timestamp php function

I need to convert a timestamp to UTC-5
The $offset is the user's timezone the values are from -12 to 12. $ds is daylight savings, if it's on, it will add an extra hour. I made this function, but I think it converts a UTC-5 timestamp to a new timestamp based on the user's timezone...I need the function to be inverted so that it returns a timestamp in UTC-5 instead. Of course the problem is much larger than this, but here's where I'm stuck. Any way to go about it?
function input_date($timestamp)
{
global $vbulletin;
$timestamp = (int)$timestamp;
if (strlen((string)$timestamp) == 10)
{
$hour = 3600.00;
$offset = $vbulletin->userinfo['timezoneoffset'];//sample -8
$ds = (int)$vbulletin->userinfo['dstonoff'];//DST values are 1 or 0
$fluff = $hour*($offset+5.00);
$timestamp = $timestamp+$fluff+($ds*$hour);
return $timestamp;//return timestamp in UTC-5 format..
}
else
{
return 0;
}
}
Whoa... talk about reinventing the wheel! And in an area notoriously hard to get right (date/time manipulation) no less.
Have you seen the DateTime and DateTimeZone classes? In addition to doing basic math, they will help you with the particular insanities of this realm of programming (per-county DST! Leap years!).
I have to ask, though, why you are doing this? The UNIX timestamp is, by definition, independent of timezones, DST, etc. It is defined precisely as the number of seconds that have elapsed since a given reference date, and the flow of time (relativistic effects notwithstanding ;-) is invariant with respect to location or the particular idiosyncrasies of lawmakers.
Maybe if you can describe in more detail what your actual goal is then we might be able to suggest a more coherent approach.

PHP DateTime for .NET developers

PHP's DateTime class has the two methods add() and sub() to add or subtract a time span from a DateTime object. This looks very familiar to me, in .NET I can do the same thing. But once I tried it, it did very strange things. I found out that in PHP, those methods will modify the object itself. This is not documented and the return value type indicates otherwise. Okay, so in some scenarios I need three lines of code instead of one, plus an additional local variable. But then PHP5's copy by reference model comes into play, too. Just copying the object isn't enough, you need to explicitly clone it to not accidently modify the original instance still. So here's the C# code:
DateTime today = DateTime.Today;
...
if (date < today.Add(TimeSpan.FromDays(7)) ...
Here's the PHP equivalent:
$today = new DateTime('today');
...
$then = clone $today;
$then->add(new DateInterval('P7D'));
if ($date < $then) ...
(I keep a copy of today to have the same time for all calculations during the method runtime. I've seen it often enough that seconds or larger time units change in that time...)
Is this it in PHP? I need to write a wrapper class for that if there's no better solution! Or I'll just stay with the good ol' time() function and just use DateTime for easier parsing of the ISO date I get from the database.
$today = time() % 86400;
...
if ($date < $today + 7 * 86400) ...
Time zones not regarded in these examples.
Update: I just found out that I can use the strtotime() function as well for parsing such dates. So what's the use for a DateTime class in PHP after all if it's so complicated to use?
Update^2: I noticed that my $today = ... thing above is garbage. Well, please just imagine some correct way of getting 'today' there instead...
It looks like you will definitely have to make a clone of the object. There does not seem to be a way to create a copy of the DateTime object any other way.
As far as I can see, you could save one line:
$today = new DateTime('today');
...
$then = clone $today;
if ($then->add(new DateInterval('P7D')) < $then) ...
I agree this isn't perfect. But do stick with DateTime nevertheless - write a helper class if need be. It is way superior to the old date functions: It doesn't have the year 2038 bug, and it makes dealing with time zones much, much easiert.

Categories