如何获得客户的确切当地时间?

无论客户端系统的时区如何,获取客户端本地时间的最佳方法是什么? 我正在创建一个应用程序,我首先需要获取客户端访问位置的确切时间和日期。 即使检测客户端系统的IP地址也有缺点,或者检测到客户端系统的时区有时可能存在风险。 那么,有什么方法可以真正可靠并且不容易出错,因为向客户显示错误的时间和日期是非常令人尴尬的。

在JavaScript? 只需实例化一个新的Date对象

var now = new Date(); 

这将创建一个具有客户端本地时间的新Date对象。

现在,您可以获得只有一行代码的用户的正确时区:

 const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; 

来源: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/resolvedOptions

然后,您可以使用moment-timezone来解析时区,如:

 const currentTime = moment().tz(timezone).format(); 

如果您想知道客户相对于GMT / UTC的时区,请转到:

 var d = new Date(); var tz = d.toString().split("GMT")[1].split(" (")[0]; // timezone, ie -0700 

如果您想要时区的实际名称,可以试试这个:

 var d = new Date(); var tz = d.toString().split("GMT")[1]; // timezone, ie -0700 (Pacific Daylight Time) 

更新1

根据您的第一个评论,您还可以使用d.getTimezoneOffset()来获取UTC的分钟偏移量。 但是夫妇的陷阱与它。

  1. 返回的分钟符号(+/-)可能与您期望的相反。 如果你落后于 UTC 8小时,它将返回480而不是-480 。 有关更多文档,请参阅MDN或MSDN 。
  2. 它实际上并没有返回客户端报告的时区,就像我给出的第二个例子一样。 只是当前从UTC偏移的分钟数。 所以它会根据夏令时变化。

更新2

虽然字符串拆分示例有效,但它们可能会令人困惑。 这是一个应该更容易理解的正则表达式版本,可能更快(虽然这两种方法都非常快)。

如果您想知道客户相对于GMT / UTC的时区,请转到:

 var gmtRe = /GMT([\-\+]?\d{4})/; // Look for GMT, + or - (optionally), and 4 characters of digits (\d) var d = new Date().toString(); var tz = gmtRe.exec(d)[1]; // timezone, ie -0700 

如果您想要时区的实际名称,请尝试以下方法:

 var tzRe = /\(([\w\s]+)\)/; // Look for "(", any words (\w) or spaces (\s), and ")" var d = new Date().toString(); var tz = tzRe.exec(d)[1]; // timezone, ie "Pacific Daylight Time" 

只是不得不解决这个问题,以为我会留下我的答案。 jQuery不需要我曾经更新过该元素,因为我已经有了缓存的对象。

我首先写了一个php函数来返回我的HTML模板所需的日期/时间

  /** * Gets the current location time based on timezone * @return string */ function get_the_local_time($timezone) { //$timezone ='Europe/London'; $date = new DateTime('now', new DateTimeZone($timezone)); return array( 'local-machine-time' => $date->format('Ymd\TH:i:s+0000'), 'local-time' => $date->format('h:i a') ); } 

然后在我的HTML模板中使用它来显示初始时间,并在数据属性中呈现javascript所需的日期格式。

     

然后我在我的日期对象上使用getUTCHours来返回时间而不管用户的时区

getUTCHours()方法根据通用时间返回指定日期和时间的小时(从0到23)。

 var initClocks = function() { var $clocks = $('.box--location__time'); function formatTime(hours, minutes) { if (hours === 0) { hours = 12; } if (hours < 10) { hours = "0" + hours; } if (minutes < 10) { minutes = "0" + minutes; } return { hours: hours, minutes: minutes } } function displayTime(time, $clockDiv) { var currentTime = new Date(time); var hours = currentTime.getUTCHours(); var minutes = currentTime.getUTCMinutes(); var seconds = currentTime.getUTCSeconds(); var initSeconds = seconds; var displayTime = formatTime(hours, minutes); $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds); setInterval(function() { if (initSeconds > 60) { initSeconds = 1; } else { initSeconds++; } currentTime.setSeconds(initSeconds); hours = currentTime.getUTCHours(); minutes = currentTime.getUTCMinutes(); seconds = currentTime.getUTCSeconds(); displayTime = formatTime(hours, minutes); $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds); }, 1000); } $clocks.each(function() { displayTime($(this).data('time'), $(this)); }); }; 

然后我使用setSeconds方法根据页面加载后的秒数(简单间隔函数)更新日期对象,并更新HTML

我的代码是

    Title       

如果你想要更多代码,请访问我的博客http://mysimplejavascriptcode.blogspot.in/

我发现显示城市或位置的本地时间的最可靠方法是使用Google时区API等时区API 。 它返回正确的时区,更重要的是,任何位置的Day Light Savings Time偏移量,就我所知,只能使用JavaScript的Date()对象。 有一个关于使用API​​来获取和显示本地时间的好教程:

 var loc = '35.731252, 139.730291' // Tokyo expressed as lat,lng tuple 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 apikey = 'YOUR_TIMEZONE_API_KEY_HERE' var apicall = 'https://maps.googleapis.com/maps/api/timezone/json?location=' + loc + '&timestamp=' + timestamp + '&key=' + apikey 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 Tokyo (timestamp + dstOffset + rawOffset) console.log(localdate.toLocaleString()) // Display current Tokyo date and time } } else{ alert('Request failed. Returned status of ' + xhr.status) } } xhr.send() // send request 

发件人: 使用JavaScript和Google时区API显示任意城市的当地时间

试试这种方式

  function timenow(){ var now= new Date(), ampm= 'am', h= now.getHours(), m= now.getMinutes(), s= now.getSeconds(); if(h>= 12){ if(h>12) h -= 12; ampm= 'pm'; } if(m<10) m= '0'+m; if(s<10) s= '0'+s; return now.toLocaleDateString()+ ' ' + h + ':' + m + ':' + s + ' ' + ampm; } toLocaleDateString() 

是一个更改日期时间格式的函数,如toLocaleDateString("en-us")