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.
-
3Are 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? – Andrew N Carr May 18 '12 at 20:49
15 Answers
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.

- 110,530
- 99
- 389
- 494

- 172,118
- 50
- 264
- 308
-
5I think he wants a way to get the timezone of a client independent of the client... – J. Holmes May 18 '12 at 20:53
-
@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. – Madara's Ghost May 18 '12 at 20:55
-
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. – mkoistinen May 18 '12 at 20:56
-
2@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. – J. Holmes May 18 '12 at 20:59
-
7@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. – Madara's Ghost May 18 '12 at 21:01
-
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. – user850234 May 19 '12 at 07:56
-
1@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? – Madara's Ghost May 19 '12 at 07:58
-
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. – user850234 May 19 '12 at 08:00
-
1@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. – Madara's Ghost May 19 '12 at 08:02
-
@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. – user850234 May 19 '12 at 08:04
-
let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/11453/discussion-between-truth-and-user850234) – Madara's Ghost May 19 '12 at 08:04
-
1I 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 issue – user850234 May 19 '12 at 08:41
-
1
-
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. – Irfandy Jip Sep 29 '19 at 11:32
-
`new Date()` won't work properly on server, because `new Date()` automatically converts to local time which server (e.g nginx) doesn't have... – DragoRoff May 08 '20 at 09:28
Nowadays you can get correct timezone of a user having just one line of code:
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
You can then use moment-timezone to parse timezone like:
const currentTime = moment().tz(timezone).format();

- 10,377
- 11
- 69
- 89

- 1,630
- 1
- 15
- 27
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.
- 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. - 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"

- 7,056
- 2
- 36
- 41
-
6In 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. – some May 19 '12 at 00:12
-
1Never 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. – pseudosavant May 21 '12 at 16:48
-
The value returned by [*Date.prototype.toString*](http://www.ecma-international.org/ecma-262/6.0/#sec-date.prototype.tostring) is entirely implementation dependent, yet this answer relies on it being standardised across all hosts. – RobG Feb 08 '16 at 23:31
-
@RobG 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. – pseudosavant Feb 11 '16 at 00:15
-
@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. – RobG Feb 11 '16 at 00:33
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());

- 106
- 1
- 2
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; }

- 686
- 7
- 9
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

- 418
- 4
- 12
-
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. – RockyK Sep 15 '18 at 23:37
-
@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 code – B''H Bi'ezras -- Boruch Hashem Sep 16 '20 at 07:24
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 + '×tamp=' + 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

- 169,008
- 28
- 173
- 236

- 1,040
- 12
- 8
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.

- 2,324
- 1
- 27
- 26
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));

- 169,008
- 28
- 173
- 236
new Date(Date.now() + (-1*new Date().getTimezoneOffset()*60000)).toISOString()

- 5,165
- 6
- 40
- 49

- 21
- 1
-
2Improve this answer by adding an explanation of how the code solves the problem. – Charlie Wallace Feb 20 '21 at 17:45
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()
}

- 661
- 1
- 9
- 25
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>

- 4,555
- 31
- 31
- 45

- 19
- 1
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)

- 3,665
- 3
- 33
- 83
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")

- 698
- 4
- 11