How to get the exact local time of client?
Asked Answered
S

15

76

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.

Skulduggery answered 18/5, 2012 at 20:47 Comment(1)
Are you trying to address a scenario where a traveling user has their device configured for time zone X, but they are currently in time zone Y?Know
J
74

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.

Jorin answered 18/5, 2012 at 20:49 Comment(15)
I think he wants a way to get the timezone of a client independent of the client...Turquoise
@32bitkid: "What is the best method to get the clients local time irrespective of the time zone of clients system?". So I beg the differ. But until OP clarifies, we cannot know.Stinky
Besides, once you have the local time, just compare it to the server time and you can easily calculate the TZ offset and therefore the TZ.Devlen
@Truth doing a new Date() on a client will be in the time zone of the OS, not the physical timezone that the box is sitting in. The latter is what the question is asking for, which is why hes asking about ip addresses and geocoding.Turquoise
@32bitkid: That's possible. But if that's what he wants, I would recommend against it. If the client wants to shoot himself in the leg by having a different time zone than the place he's actually staying, he probably has a good reason. In which case, you as a programmer should respect that.Stinky
Recently i had an issue with the client in which the timezone set in the system was different from the timezone currently the client was. This resulted in an inefficient output of the application. So was looking for something from which i can get the client timezone irrespective of the system timezone or alternative way could be to just get the timezone from client system and then update the current date and time according to the timezone local time.Skulduggery
@user850234: Please give us some context. I don't see any reason why you would need the actual time zone and not the time zone the client reported to you. If he wants to pretend he lives in China, who are you to tell him not to?Stinky
But is there a way so that i can get the local time by just detecting the timezone of client system because if the system date or time is set wrong then the calculation comes wrong. I tried to create a new Date objecr with the client's local time but if the client is in different timezone and the timezone set in the system is different but the date and time is set according to the current location then the calculation comes wrong.Skulduggery
@user850234: You aren't answering my question. WHAT are you trying to do? Not HOW you're trying to do it. What does your application do? Why do you need to know the client's actual time zone instead of the one he reported he's using.Stinky
@truth : The reason is i have some live channels which is shown according to the timezone. So if a user pretends to be in china but is in dubai then what to do. Which channel to show and how to get the time because date object gives the timzone and the client system date and time. If the client set the time and date according to dubai standard but the time is china then UTC time conversion calculation comes wrong.Skulduggery
let us continue this discussion in chatStinky
I have done the application using the client timezone but what will be the case when a client is in different timezone but want to see the current timezone time and not what the timezone is set in the system bcause a normal user can be ignorant of the time zone issueSkulduggery
this is not local time of clientColicweed
I'm using new Date() but it doesn't show correctly in my timezone. But it's showing an incorrect date and time. However, it shows the right 'GMT' number.Eggett
new Date() won't work properly on server, because new Date() automatically converts to local time which server (e.g nginx) doesn't have...Antimere
G
35

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();
Gannet answered 26/8, 2016 at 7:52 Comment(2)
Is this dependent on the client thoughErb
Moment.js is now deprecatedNobie
P
27

Try

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

console.log(s);
Prouty answered 24/11, 2019 at 23:41 Comment(0)
S
12

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"
Salomo answered 18/5, 2012 at 20:59 Comment(5)
In my opinion there is a much better way to get the offset to UTC: d.getTimezoneOffset(). It returns the offset of UTC in number of minutes.Stellular
Never used that. Good tip. There is one thing it doesn't do that the second example I give does do though, it doesn't actually tell you the timezone. The response changes (like my first example) based on whether it is daylight savings time or not.Salomo
The value returned by Date.prototype.toString is entirely implementation dependent, yet this answer relies on it being standardised across all hosts.Cesena
@Cesena that is totally correct. In theory implantations could vary, but it practice Edge, Blink, Webkit, and Gecko (which cover 99% of browsers) all function the same as far as this capability is concerned. That could change in the future but it is unlikely. There isn't a perfect solution to this problem.Salomo
@pseudosavant—the "perfect solution" is getTimezoneOffset, which reports exactly what the system offset is set to. There is no standard for timezone abbreviations, e.g. EST might be one of three time zones. There is no answer to the OP (i.e. determine time zone independently of system settings) that doesn't require some way of determining the host location and a database of time boundaries and time change rules such as daylight saving other than just asking the user.Cesena
T
10

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());
Triacid answered 30/9, 2020 at 14:1 Comment(0)
G
6
  • directly like this :

    new Date((new Date().setHours(new Date().getHours() - (new Date().getTimezoneOffset() / 60)))).toISOString()
    
  • more details in this utility function

    function getLocaLTime() {
      // new Date().getTimezoneOffset() : getTimezoneOffset in minutes 
      //for GMT + 1 it is (-60) 
      //for GMT + 2 it is (-120) 
      //..
      let time_zone_offset_in_hours = new Date().getTimezoneOffset() / 60;
      //get current datetime hour
      let current_hour = new Date().getHours();
      //adjust current date hour 
      let local_datetime_in_milliseconds = new Date().setHours(current_hour - time_zone_offset_in_hours);
      //format date in milliseconds to ISO String
      let local_datetime = new Date(local_datetime_in_milliseconds).toISOString();
      return local_datetime;
      }
    
Giaimo answered 29/4, 2021 at 14:50 Comment(0)
E
3

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

Elevenses answered 3/9, 2015 at 12:38 Comment(2)
The Op requested this only using javascript. Using PHP as well sort of defeats the purpose, as PHP has a lot of functions to do this as well.Mudslinging
@rocky well it's impossible to use only JavaScript, unless you also use nodeJS, because at some point it has to connect to an API that is powered by server side codeErb
C
3

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

Conservatism answered 12/11, 2016 at 22:31 Comment(0)
T
2

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.

Tatouay answered 22/10, 2020 at 14:58 Comment(0)
P
2
new Date(Date.now() + (-1*new Date().getTimezoneOffset()*60000)).toISOString()
Protoplast answered 20/2, 2021 at 17:23 Comment(1)
Improve this answer by adding an explanation of how the code solves the problem.Courtroom
E
1

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

fetch("https://worldtimeapi.org/api/ip")
  .then(response => response.json())
  .then(data => console.log(data.dst,data.datetime));
Elane answered 16/9, 2020 at 7:45 Comment(0)
X
1

I needed to report to the server the local time something happened on the client. (In this specific business case UTC provides no value). I needed to use toIsoString() to have the format compatible with .Net MVC but toIsoString() this always converts it to UTC time (which was being sent to the server).

Inspired by the 'amit saini' answer I now use this

    function toIsoStringInLocalTime(date) {
        return new Date((date.getTime() + (-date.getTimezoneOffset() * 60000))).toISOString()
    }
Xerosere answered 15/4, 2021 at 12:16 Comment(0)
P
0

my code is

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();
}
<body onload=display_ct();>
  <span id='ct' ></span>
</body>
Prisilla answered 7/7, 2014 at 5:45 Comment(0)
C
0

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)
Charity answered 16/9, 2020 at 7:30 Comment(0)
H
-1

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

Hexyl answered 22/8, 2014 at 6:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.