I get the Error sometime on Converting 12hour format time from a Timezone to new
TimeZone
Error:
Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (00:00:31 AM) at position 9 (A): The timezone could not be found in the database' in C:\xampp\php\udp.php:105
Stack trace:
#0 C:\xampp\php\udp.php(105): DateTime->__construct('00:00:31 AM', Object(DateTimeZone))
#1 {main} thrown in C:\xampp\php\udp.php on line 105
MyCodes:
// $gps_time = "9:43:52";
$gps_time = $time_hour.":".$time_min.":".$time_sec;
// $time_received = "01:45:04 2012-07-28";
$time_received = date('H:i:s Y-m-d');
$utc = new DateTimeZone("UTC");
$moscow = new DateTimeZone("Europe/Moscow");
//Instantiate both AM and PM versions of your time
$gps_time_am = new DateTime("$gps_time AM", $utc);
$gps_time_pm = new DateTime("$gps_time PM", $utc);
//Received time
$time_received = new DateTime($time_received, $moscow);
//Change timezone to Moscow
$gps_time_am->setTimezone($moscow);
$gps_time_pm->setTimezone($moscow);
//Check the difference in hours. If it's less than 1 hour difference, it's the correct one.
if ($time_received->diff($gps_time_pm)->h < 1) {
$correct_time = $gps_time_pm->format("H:i:s Y-m-d");
}
else {
$correct_time = $gps_time_am->format("H:i:s Y-m-d");
}
echo $correct_time;
Question: Where’s the problem !!?
P.S: above Code is a part of my udp socket and run from php cli
Summary
Put simply, that PHP is trying (mistakenly, for your needs) to read
AMas a timezone andAMis not a valid timezone.Details
10:39:6 AMgets separated into the following pieces10:39:6it recognises astimelong24(a 24-hour formatted time with seconds)AMit recognises astz(timezone).In contrast, for
10:39:06 AMit correctly parses the whole string astimelong12(a 12-hour formatted time with seconds and AM/PM).Boring bit
The reason for this strange behaviour lies in the date parsing logic (source). The relevant patterns are:
timelong24
timelong12
As you can see, to match the
timelong12format (which is what we really wanted), the seconds portion of the time must be double-digits.