1. 程式人生 > >使用Google時區API顯示任何城市的實時本地時間

使用Google時區API顯示任何城市的實時本地時間

現在我們知道如何可靠地任何地點的日期和時間感謝Google時區API,我們可以用它做任何事情-標準的JavaScriptDate物件允許我們。一個流行的擴充套件是顯示時間在,嗯,實時的:

例子:

東京時間:下午2:19:02 (Thur)

洛杉磯時間:下午10:19:02 (Wed)

多倫多時間:上午1:19:02 (Thur)

巴黎時間:上午7:19:02 (Thur)

這是函式currentlocaltime()魔術背後。它採用任何緯度和經度元組,並在DIV中顯示相應的生命時間:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

<div class="timebox">Tokyo Time: <span id=

"tokyotime"></span></div>

<div class="timebox">LA Time: <span id="latime"></span></div>

<div class="timebox">Toronto Time: <span id="torontotime"></span></div>

<div class="timebox">Paris Time: <span id="paristime"></span></div>

<script>

var apikey = 'YOUR_API_KEY_HERE'

var daysofweek = ['Sun', 'Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun']

function currentlocaltime(divid, loc){

var container = document.getElementById(divid)

var targetDate = new Date() // Current date/time of user computer

var timestamp = targetDate.getTime()/1000 + targetDate.getTimezoneOffset() * 60 // Current UTC date/time expressed as seconds since midnight, January 1, 1970 UTC

var xhr = new XMLHttpRequest() // create new XMLHttpRequest2 object

xhr.open('GET', apicall) // open GET request

xhr.onload = function(){

if (xhr.status === 200){ // if Ajax request successful

var output = JSON.parse(xhr.responseText) // convert returned JSON string to JSON object

console.log(output.status) // log API return status for debugging purposes

if (output.status == 'OK'){ // if API reports everything was returned successfully

var offsets = output.dstOffset * 1000 + output.rawOffset * 1000 // get DST and time zone offsets in milliseconds

var localdate = new Date(timestamp * 1000 + offsets) // Date object containing current time of target location

var refreshDate = new Date() // get current date again to calculate time elapsed between targetDate and now

var millisecondselapsed = refreshDate - targetDate // get amount of time elapsed between targetDate and now

localdate.setMilliseconds(localdate.getMilliseconds()+ millisecondselapsed) // update localdate to account for any time elapsed

setInterval(function(){

localdate.setSeconds(localdate.getSeconds()+1)

container.innerHTML = localdate.toLocaleTimeString() + ' (' + daysofweek[ localdate.getDay() ] + ')'

}, 1000)

}

}

else{

alert('Request failed.  Returned status of ' + xhr.status)

}

}

xhr.send() // send request

}

currentlocaltime('tokyotime', '35.731252, 139.730291')

currentlocaltime('latime', '34.052046, -118.259335')

currentlocaltime('torontotime', '43.656090, -79.387679')

currentlocaltime('paristime', '48.856805, 2.348242')

</script>

突出顯示的行從我們已經看到的程式碼中選擇什麼是新的在上一頁給時間帶來生命。一次電流localdate已經檢索到,我們通過建立另一個例項來確保它儘可能地是當前的。Date()物件來計算連線到Google時區API所需的毫秒數,並將該額外時間(以毫秒為單位)附加到localdate物件。

最新的localdate物件,剩下的就是每秒鐘增加1秒,並將結果顯示給世界其他人!