[javascript] How to get the exact local time of client?

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.

This question is related to javascript jquery datetime geolocation timezone

The answer is


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.


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"

In order to get local time in pure Javascript use this built in function

// return new Date().toLocaleTimeString();

See below example

 function getLocaltime(){
   return new Date().toLocaleTimeString();
 }
 console.log(getLocaltime());

Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api

_x000D_
_x000D_
fetch("https://worldtimeapi.org/api/ip")
  .then(response => response.json())
  .then(data => console.log(data.dst,data.datetime));
_x000D_
_x000D_
_x000D_


Try

_x000D_
_x000D_
let s= new Date().toLocaleString();_x000D_
_x000D_
console.log(s);
_x000D_
_x000D_
_x000D_


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

You can also make your own nodeJS endpoint, publish it with something like heroku, and access it

require("http").createServer(function (q,r) {
    r.setHeader("accees-control-allow-origin","*")
    r.end(Date.now())
}).listen(process.env.PORT || 80)

Then just access it on JS

fetch ("http://someGerokuApp")
.then(r=>r.text)
. then (r=>console.log(r))

This will still be relative to whatever computer the node app is hosted on, but perhaps you can get the location somehow and provide different endpoints fit the other timezones based on the current one (for example if the server happens to be in California then for a new York timezone just add 1000*60*60*3 milliseconds to Date.now() to add 3 hours)

For simplicity, if it's possible to get the location from the server and send it as a response header, you can just do the calculations for the different time zones in the client side

In fact using heroku they allow you to specify a region that it should be deployed at https://devcenter.heroku.com/articles/regions#specifying-a-region you can use this as reference..

EDIT just realized the timezone is in the date string itself, can just pay the whole thing as a header to be read by the client

require("http").createServer(function (q,r) {
    var d= new Date()
    r.setHeader("accees-control-allow-origin","*")
    r.setHeader("zman", d.toString())
    r.end(d.getTime())
}).listen(process.env.PORT || 80)

I found this function is very useful during all of my projects. you can also use it.

getStartTime(){
    let date = new Date();
    var tz = date.toString().split("GMT")[1].split(" (")[0];
    tz = tz.substring(1,5);
    let hOffset = parseInt(tz[0]+tz[1]);
    let mOffset = parseInt(tz[2]+tz[3]);
    let offset = date.getTimezoneOffset() * 60 * 1000;
    let localTime = date.getTime();
    let utcTime = localTime + offset;
    let austratia_brisbane = utcTime + (3600000 * hOffset) + (60000 * mOffset);
    let customDate = new Date(austratia_brisbane);

    let data = {
        day: customDate.getDate(),
        month: customDate.getMonth() + 1,
        year: customDate.getFullYear(),
        hour: customDate.getHours(),
        min: customDate.getMinutes(),
        second: customDate.getSeconds(),
        raw: customDate,
        stringDate: customDate.toString()
    }

    return data;
  }

this will give you the time depending on your time zone.

Thanks.


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


new Date(Date.now() + (-1*new Date().getTimezoneOffset()*60000)).toISOString()

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


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


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/


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to geolocation

getCurrentPosition() and watchPosition() are deprecated on insecure origins Can we locate a user via user's phone number in Android? What is meaning of negative dbm in signal strength? How to get current location in Android Google API for location, based on user IP address How to get a time zone from a location using latitude and longitude coordinates? How to display my location on Google Maps for Android API v2 Getting visitors country from their IP Does GPS require Internet? How to calculate distance from Wifi router using Signal Strength?

Examples related to timezone

How to set the timezone in Django? How to convert Moment.js date to users local timezone? What does this format means T00:00:00.000Z? How do I get the current timezone name in Postgres 9.3? MySQL JDBC Driver 5.1.33 - Time Zone Issue Python get current time in right timezone Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings PHP date() with timezone? How to store a datetime in MySQL with timezone info Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST