我从 GPS 跟踪器收到 12 小时时间格式。
例如,GPS 时间:8:25:40
在 GMT0(12 小时格式)中
发送的 GPS 时间延迟可能在 1~20 分钟的范围内
从 GPS 接收时间,时区 00:2:15
延迟2012-07-27 23:27:55
Europe/Moscow
PS:以上数据,我的GPS时间的结果一定是2012-07-27 23:25:40
问题:
如何在我的时区 (Europe/Moscow
) 中指定 GPS 时间?
$gps_time = "9:43:52";
$time_received = "01:45:04 2012-07-28";
$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) {
echo $gps_time_pm->format("H:i:s Y-m-d");
}
else {
echo $gps_time_am->format("H:i:s Y-m-d");
}
确保指定接收时间的确切日期,以防止出现异常。
PS莫斯科在欧洲。
<?php
function correct_time($time)
{
$yesterday = false;
$tomorrow = false;
#offset = abs(date('h') - (int) $time);
$offset = '3';
$time_of_day = ($hour < 12)? 'AM': 'PM';
if($hour < 0)
{
$yesterday = true;
$time_of_day = 'PM';
}
if($hour > 12)
{
$tomorrow = true;
$time_of_day = 'AM';
}
$screwed_gps_time = $time . ' ' . $time_of_day;
$gps_time = new DateTime($screwed_gps_time, new DateTimeZone("Europe/London"));
if($yesterday)
{
$gps_time->sub(new DateInterval('P1D'));
}
if($tomorrow)
{
$gps_time->add(new DateInterval('P1D'));
}
$gps_time->setTimezone(new DateTimeZone("Europe/Moscow"));
return $gps_time->format("Y-m-d H:i:s");
}
echo correct_time('8:25:40'); # 2012-07-27 23:25:40
echo correct_time('1:25:40'); # 2012-07-28 04:25:40
echo correct_time('11:25:40'); # 2012-07-28 02:25:40
案例太多,这里就不一一介绍了
我不记得我所有的 PHP 库,所以
伪代码算法:
AdjustTimeToGPS(gpsTime : 12HourTime, currentTime : DayAndTime, currentTimeZone : TimeZone) : DayAndTime
begin
gmtCurrentTime : DayAndTime := ConvertToGmt(currentTime, currentTimeZone);
gmtCurrent12HourTime : 12HourTime := 12HourFromDayAndTime(gmtCurrentTime);
gpsHour : Hour := GetHourFrom12HourTime(gpsTime); // hour is 0 to 11;
gmtCurrentHour : Hour := GetHourFrom12HourTime(gmtCurrent12Hour);
day : Day := GetDayFromDayAndTime(gmtCurrentTime);
isPm : Boolean = IsPM(gmtCurrentTime);
if (gmtCurrentHour == 0 AND gpsHour == 11)
begin
// we need to subtract 12 hours
isPm := Not(isPm);
if (isPM)
begin
// we looped. need to subtract a day
day := day - 1;
end
end
if (gmtCurrentHour == 11 AND gpsHour == 0)
begin
// we need to add 12 hours
isPm := Not(isPm);
if (Not(isPM))
begin
// we looped. need to add a day
day := day + 1;
end
end
return DayAndTimeFrom12Hour(gpsTime, isPM, day);
end