Calculating JS dates using UTC on a server?

I am transmitting the UTC date from the server, and I need JS to find the difference in seconds between the "now" and the date transmitted from the server.

I'm trying to do something like

var lastUpdatedDate = moment(utcStringFromServer);
var currentDate = moment();
var diff = currentDate - lastUpdatedDate;
Problem

lies in the fact that this gives a very invalid answer, since UTC leaves the server, and creating a new one moment()makes it local. How can I make a calculation with respect to full UTC so that it is an agnostic of any local time?

+4
source share
3 answers

, , , , 1 1970 UTC. / , / UTC, / .

, +dateVar dateVar.valueOf() , 01/01/1970T00: 00: 00Z.

, , UTC ( , ISO String), Javascript Date, , .

, , , UTC, UTC. , new Date().

, , , , , . , .

+2

, , :

    var lastUpdatedDate = moment(utcStringFromServer);
    var date = Date.UTC();
    var currentDate = moment(date);
    var diff = currentDate - lastUpdatedDate;
0

, utcStringFromServer :

Fri, 19 Aug 2016 04:27:27 GMT

If so, you do not need Moment.js at all. If you pass this string to Date.parse(), it will return the number of milliseconds since January 1, 1970. Then you can use the button .toISOString()to get the same information right now (converted to UTC) and analyze it in the same way to get milliseconds since 1970. You can then subtract the first from the last and divide it by 1000 to convert back to seconds.

In general, it would look something like this:

var lastUpdatedDate = Date.parse(utcStringFromServer);
var currentDate = Date.parse((new Date()).toISOString())
var diff = (currentDate - lastUpdatedDate) / 1000.0; // Convert from milliseconds
0
source

Source: https://habr.com/ru/post/1651734/


All Articles