Javascript 如何获取客户端的确切当地时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10659523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:24:28  来源:igfitidea点击:

How to get the exact local time of client?

javascriptjquerydatetimegeolocationtimezone

提问by user850234

What is the best method to get the clients local time irrespective of the time zone of clients system? I am creating an application and i need to first of all get the exact time and date of the place from where the client is accessing. Even detecting the ip address of client system has a drawback or detecting the time zone of client system may be risky at times. So, is there any way out which could be really reliable and not vulnerable to error because displaying wrong time and date to client is something very embarassing.

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

回答by Madara's Ghost

In JavaScript? Just instantiate a new Date object

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

var now = new Date();

That will create a new Date object with the client's local time.

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

回答by Stanislau Buzunko

Nowadays you can get correct timezone of a user having just one line of code:

如今,您只需一行代码即可获得用户的正确时区:

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

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

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

You can then use moment-timezoneto parse timezone like:

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

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

回答by pseudosavant

If you want to know the timezone of the client relative to GMT/UTC here you go:

如果你想知道客户端相对于 GMT/UTC 的时区,你可以:

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

If you'd like the actual name of the timezone you can try this:

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

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

UPDATE 1

更新 1

Per the first comment by you can also use d.getTimezoneOffset()to get the offset in minutes from UTC. Couple of gotchas with it though.

根据您的第一条评论,您还可以使用d.getTimezoneOffset()以分钟为单位从 UTC 获取偏移量。不过有几个问题。

  1. The sign (+/-) of the minutes returned is probably the opposite of what you'd expect. If you are 8 hours behindUTC it will return 480not -480. See MDNor MSDNfor more documentation.
  2. It doesn't actually return what timezone the client is reporting it is in like the second example I gave. Just the minutes offset from UTC currently. So it will change based on daylight savings time.
  1. 返回的分钟数的符号 (+/-) 可能与您期望的相反。如果你是8小时背后UTC将返回480不能-480。有关更多文档,请参阅MDNMSDN
  2. 它实际上并没有像我给出的第二个例子那样返回客户端报告它所在的时区。只是当前与 UTC 的分钟偏移量。所以它会根据夏令时而改变。

UPDATE 2

更新 2

While the string splitting examples work they can be confusing to read. Here is a regex version that should be easier to understand and is probably faster (both methods are very fast though).

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

If you want to know the timezone of the client relative to GMT/UTC here you go:

如果你想知道客户端相对于 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, i.e. -0700

If you'd like the actual name of the timezone try this:

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

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, i.e. "Pacific Daylight Time"

回答by MrBizle

Just had to tackle this so thought I would leave my answer. jQuery not required I used to update the element as I already had the object cached.

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

I first wrote a php function to return the required dates/times to my HTML template

我首先编写了一个 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('Y-m-d\TH:i:s+0000'),
        'local-time' => $date->format('h:i a')
    );

}

This is then used in my HTML template to display an initial time, and render the date format required by javascript in a data attribute.

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

        <span class="box--location__time" data-time="<?php echo $time['local-machine-time']; ?>">
            <?php  echo $time['local-time']; ?>
        </span>

I then used the getUTCHours on my date object to return the time irrespective of the users timezone

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

The getUTCHours() method returns the hour (from 0 to 23) of the specified date and time, according to universal time.

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));

    });

};

I then use the setSeconds method to update the date object based on the amount of seconds past since page load (simple interval function), and update the HTML

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

回答by Kamil Kie?czewski

Try

尝试

let s= new Date().toLocaleString();

console.log(s);

回答by coco puffs

The most reliable way I've found to display the local time of a city or location is by tapping into a Time Zone API such as Google Time Zone API. It returns the correct time zone, and more importantly, Day Light Savings Time offset of any location, which just using JavaScript's Date() object cannot be done as far as I'm aware. There's a good tutorial on using the API to get and display the local time here:

我发现显示城市或地点当地时间的最可靠方法是利用时区 API,例如Google Time Zone API。它返回正确的时区,更重要的是,任何位置的夏令时偏移量,据我所知,仅使用 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

From: Displaying the Local Time of Any City using JavaScript and Google Time Zone API

来自:使用 JavaScript 和 Google Time Zone API 显示任何城市的本地时间

回答by user3768731

my code is

我的代码是

  <html>
  <head>
  <title>Title</title>
  <script type="text/javascript"> 
  function display_c(){
  var refresh=1000; // Refresh rate in milli seconds
  mytime=setTimeout('display_ct()',refresh)
  }

  function display_ct() {
  var strcount
  var x = new Date()
  document.getElementById('ct').innerHTML = x;
  tt=display_c();
  }
  </script>
  </head>

  <body onload=display_ct();>
  <span id='ct' ></span>

  </body>
  </html>

if you want more codes visit my blog http://mysimplejavascriptcode.blogspot.in/

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

回答by Sumit

Try on this way

试试这个方法

    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()

is a function to change the date time format like toLocaleDateString("en-us")

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