i am printing a timestamp in console of chrome browser using following code,
moment("2021-01-12 00:00:00").utc().utcOffset(-new Date().getTimezoneOffset()).format('x')
this line prints the timestamp at given time and date.
if i change timezone from “windows Date and time settings” , the output of above line also changes .
how can i make output of above line constant irrespective of timezone of current browser window ?
Advertisement
Answer
The documentation for Date.protoype.getTime() states:
The getTime() method returns the number of milliseconds* since the Unix Epoch.
* JavaScript uses milliseconds as the unit of measurement, whereas Unix Time is in seconds.
getTime() always uses UTC for time representation. For example, a client browser in one timezone, getTime() will be the same as a client browser in any other timezone.
As such the timestamp you get from a Date is always UTC with timezone information taken from the host environment (OS).
By default JavaScript (and moment) will parse dates and times assuming they are in the user’s local timezone and therefore affected by changes to Windows date and time settings.
To keep it consistent you need to tell moment to parse the value as UTC.
const timestamp = moment.utc("2021-01-12 00:00:00").format("x"); console.log(timestamp); // prints 1610409600000
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
No matter which timezone you’re in, you should get the value 1610409600000
logged to the console.