Reputation: 4868
I have a table with date/time information stored as strings. Due to poor planning, some of the strings have a timezone in them (e.g., "2014-01-13 04:22 -8"
) and others don't ("2014-01-13 04:22"
). Either type of string works fine with strtotime()
or new DateTime()
but once I do that, the information about whether there was a timezone is lost -- strings without a timezone are assigned the server's default timezone. Is there a function I can use to find out whether the string contains a timezone identifier?
It seems trivial to write a regex for this, but experience tells me that date formats have enough variation and weird special cases that it's always better to use built-in functions when possible.
Upvotes: 3
Views: 2781
Reputation: 18440
You haven't necessarily lost the information as to whether or not there was a timezone in the date/time string once you have created your DateTime object. If you do a var_dump()
on a DateTime object, you will get output like this:-
object(DateTime)[1]
public 'date' => string '2014-01-13 04:22:00' (length=19)
public 'timezone_type' => int 1
public 'timezone' => string '-08:00' (length=6)
As you can see, the timezone type and the value of the timezone passed are both there, it is just a matter of fishing them out.
In your case I think that you just need to know if a TZ string was passed in the date/time string. If it was, then the timezone type will be 1, if no string was present, then the default system timezone will have been used and will be of type 3.
You cannot get the timezone type directly, but the following function will get it for you and you can then act accordingly.
function getTZType(\DateTime $date)
{
ob_start();
var_export($date);
$dateString = ob_get_clean();
preg_match('%=>.\d%', $dateString, $matches);
return (int)explode(' ', $matches[0])[1];
}
$date = new \DateTime('2014-01-13 04:22 -8');
echo getTZType($date);
The function returns an int 1,2 or 3 that corresponds to the time zone type explained in my answer here.
This method will allow you to avoid using regex on date/time strings, the regex that is used is on a string with a known and reliable format.
Upvotes: 1
Reputation: 57719
a regexp like:
$str = "2014-01-13 04:22 -8"
$has_timezone = preg_match(/[-+][0-9]{1,2}$/, $str);
Look for +
or -
followed by 1 or 2 numbers, at the end of the string.
If you input also conains:
2004-10-10
the -10
will be detected as a timezone so perhaps add a [space] detection:
$has_timezone = preg_match(/\s[-+][0-9]{1,2}$/, $str);
If your timestamp strings are always:
YYYY-mm-dd HH:ii[ timezone]
then even a simple strlen
check is sufficient. 16 = no timezone, 17+ = timezone.
Upvotes: 2