Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

javascript - Make time independent of browser time zone

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 ?

question from:https://stackoverflow.com/questions/65844870/make-time-independent-of-browser-time-zone

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...