Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 659
user850234 Avatar asked May 18 '12 20:05

user850234


People also ask

How do I get local user time?

var currentTime = new Date(); var hours = currentTime. getHours(); var minutes = currentTime. getMinutes(); if (minutes < 10) { minutes = "0" + minutes; } document. write("<b>" + hours + ":" + minutes + " " + "</b>");

What is local time in JS?

LocalTime is an immutable date-time object that represents a time, often viewed as hour-minute-second. Time is represented to nanosecond precision. For example, the value '13:45.30. 123456789' can be stored in a LocalTime.

How do I check my browser time zone?

Open DevTools in Chrome -> Open the Console drawer. Click on the three-dotted menu -> Click on More tools -> Sensors. From the Sensors tab, set the location according to your preference and define the specific timezone.

How do I get timezone offset?

Definition and UsagegetTimezoneOffset() returns the difference between UTC time and local time. getTimezoneOffset() returns the difference in minutes. For example, if your time zone is GMT+2, -120 will be returned.


2 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.

like image 197
Madara's Ghost Avatar answered Sep 30 '22 03:09

Madara's Ghost


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(); 
like image 43
Stanislau Buzunko Avatar answered Sep 30 '22 03:09

Stanislau Buzunko