How to get the exact local time of client?

2019-01-07 17:46发布

问题:

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.

回答1:

In JavaScript? Just instantiate a new Date object

var now = new Date();

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



回答2:

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

You can then use moment-timezone to parse timezone like:

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


回答3:

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

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

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.

  1. The sign (+/-) of the minutes returned is probably the opposite of what you'd expect. If you are 8 hours behind UTC it will return 480 not -480. See MDN or MSDN for 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.

UPDATE 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:

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"


回答4:

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.

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

 /**
 * 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.

        <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

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

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



回答5:

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/



回答6:

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:

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



回答7:

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