我的数据库中有多个日期时间和位置存储为字符串。有些日期已经按照我想要的方式格式化了:
Apr 29, 2017 09:00 EDT
但很多人都错过了这个时区,我想对那些没有时区的人做以下事情:
Jun 25 2017 15:00
且我的位置为纽约,则应返回EDT
(不是EST
)< / LI>
醇>
另外,我是否必须构建自己的查找表来翻译像America/New_York
这样的php时区,或者是否有内置函数来处理这个问题?
当我尝试使用以下方法转换其中一些时:
date('M j, Y H:i T', strtotime($mydatetimestring))
所有人都有UTC
最后加上,包括那些已经有时区的人。我需要将每个日期时间保存在数据库中存储的各自时区中,而不是将它们全部转换为/来自UTC。
答案 0 :(得分:0)
嗯,这需要进行大量的调整和研究,但这是解决方案,希望它可以帮助别人。有几个步骤可以实现我想要的目标:
strtotime
以下是代码:
$fix_time_string = $myqueryresult;
foreach ($fix_time_string as $fix_time_string_record) {
$convertone = strtotime($fix_time_string_record->my_datetime_string);
if ($convertone) { //Check that my datetime string is convertable first
$address = $fix_time_string_record->my_location_string;
if ($address !== '') { // Check that I have an address
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&key=MY_GEOCODE_API_KEY');
$obj = json_decode($json);
if (!$obj->status[0] == 'ZERO_RESULTS') { //Don't do the following if there is no result from google for the address
$lat = $obj->results[0]->geometry->location->lat;
$lng = $obj->results[0]->geometry->location->lng;
$jsonzone = file_get_contents('https://maps.googleapis.com/maps/api/timezone/json?location=' . $lat . ',' . $lng . '×tamp=' . $convertone . '&key=MY_TIMEZONE_API_KEY');
$objzone = json_decode($jsonzone);
// Set up my conversions from google's timeZoneName
if ($objzone->timeZoneName == "Pacific Standard Time") {
$tzabbr = "PST";
} elseif ($objzone->timeZoneName == "Pacific Daylight Time") {
$tzabbr = "PDT";
} elseif ($objzone->timeZoneName == "Mountain Standard Time") {
$tzabbr = "MST";
} elseif ($objzone->timeZoneName == "Mountain Daylight Time") {
$tzabbr = "MDT";
} elseif ($objzone->timeZoneName == "Central Standard Time") {
$tzabbr = "CST";
} elseif ($objzone->timeZoneName == "Central Daylight Time") {
$tzabbr = "CDT";
} elseif ($objzone->timeZoneName == "Eastern Standard Time") {
$tzabbr = "EST";
} elseif ($objzone->timeZoneName == "Eastern Daylight Time") {
$tzabbr = "EDT";
}
// format and create my new value
$newtimevalue = date('M j, Y H:i', strtotime($fix_time_string_record->my_datetime_string)) . " " . $tzabbr;
// update my values in the db (wordpress here btw)
update_post_meta($fix_time_string_record->ID, 'my_datetime_string', $newtimevalue, $fix_time_string_record->my_datetime_string);
// echo what I did
echo $fix_time_string_record->ID . " changed from " . $fix_time_string_record->my_datetime_string . " to " . $newtimevalue . "<br>";
} else {
echo $fix_time_string_record->ID . " can't get lat long from this ID for some reason. <br>";
}
} else {
echo $fix_time_string_record->ID . " has an empty address, can't get timezone without location <br>";
}
} else {
echo $fix_time_string_record->ID . " UNCONVERTABLE datetime string <br>";
}
// show output after each iteration
flush();
ob_flush();
}