我有一個像印度奧里薩邦布巴內斯瓦爾這樣的地方的格式化地址。如何在php代碼中獲得這個地方的時區,即「Asia/Calcutta」?如何在php中獲得某個地點的時區
我可以得到這個使用googlemapapi即首先我得到經緯度和長從這個地址,並使用這個緯度和經度和谷歌時區API密鑰我得到的時區在javascript中。
我想純粹的PHP代碼的時區。我可以嗎 ?
感謝Avd
我有一個像印度奧里薩邦布巴內斯瓦爾這樣的地方的格式化地址。如何在php代碼中獲得這個地方的時區,即「Asia/Calcutta」?如何在php中獲得某個地點的時區
我可以得到這個使用googlemapapi即首先我得到經緯度和長從這個地址,並使用這個緯度和經度和谷歌時區API密鑰我得到的時區在javascript中。
我想純粹的PHP代碼的時區。我可以嗎 ?
感謝Avd
當然可以。試着用file_get_contents()
:
<?php
$url = "https://maps.googleapis.com/maps/api/timezone/json?location=20,85×tamp=1393575206&sensor=false";
$json_timezone = file_get_contents($url);
print_r($json_timezone);
?>
這將打印:
{ "dstOffset" : 0, "rawOffset" : 19800, "status" : "OK", "timeZoneId" : "Asia/Calcutta", "timeZoneName" : "India Standard Time" }
當前時間戳或與您所要的日期/時間的時間戳替換時間戳。
public function getTimezone($location)
{
$location = urlencode($location);
$APIkey = "PLACE API KEY HERE";
if(!$APIkey){ return false;}
$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$location}&key=$APIkey";
$data = file_get_contents($url);
// Get the lat/lng out of the data
$data = json_decode($data);
if(!$data) return false;
if(!is_array($data->results)) return false;
if(!isset($data->results[0])) return false;
if(!is_object($data->results[0])) return false;
if(!is_object($data->results[0]->geometry)) return false;
if(!is_object($data->results[0]->geometry->location)) return false;
if(!is_numeric($data->results[0]->geometry->location->lat)) return false;
if(!is_numeric($data->results[0]->geometry->location->lng)) return false;
$lat = $data->results[0]->geometry->location->lat;
$lng = $data->results[0]->geometry->location->lng;
// get the API response for the timezone
//$timezoneAPI = "https://maps.googleapis.com/maps/api/timezone/json?location={$lat},{$lng}×tamp=1331161200&key=AIzaSyBtEwgQX2k0fijo3EsFlOLgXxEvkDpDyeI";
$timezoneAPI = "http://api.geonames.org/timezoneJSON?lat={$lat}&lng={$lng}&username=demo";
$response = file_get_contents($timezoneAPI);
if(!$response)
return false;
$response = json_decode($response);
if(!is_object($response))
return false;
if(isset($response->timezoneId) && !is_string($response->timezoneId)) // If google api, use timeZoneId
return false;
return $response->timezoneId;
}
請使用此功能
這個問題特別要求解決方案是「純粹的PHP代碼」。該代碼仍然使用幾個外部API;您剛剛替換Google地圖時區API的GeoNames API。 (使用「演示」帳戶,不應在生產代碼中使用...) – duskwuff
如果你發現這個線程,然後看看timezoneapi.io。
使用地址API,您可以請求地址。該請求返回:
在PHP
// Get JSON object
$jsondata = file_get_contents("https://timezoneapi.io/api/address/?Hacker+Way+1+Menlo+Park+California");
// Decode
$data = json_decode($jsondata, true);
// Request OK?
if($data['meta']['code'] == '200'){
// Example: Get the city parameter
echo "City: " . $data['data']['addresses']['0']['city'] . "<br>";
// Example: Get the users time
echo "Time: " . $data['data']['addresses']['0']['datetime']['date_time_txt'] . "<br>";
}
你嘗試映射國家名稱到時區? – anurupr
你想設置默認時間爲亞洲/加爾各答? – Prafulla
嘗試使用Yahoo Placefinder等服務。 –