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.
var currentTime = new Date(); var hours = currentTime. getHours(); var minutes = currentTime. getMinutes(); if (minutes < 10) { minutes = "0" + minutes; } document. write("<b>" + hours + ":" + minutes + " " + "</b>");
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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With