Calculate time difference between utc date and given date in Javascript

In Javascript, I want to calculate the difference between today’date (but adjusted to GMT0) and a given date 1970/01/01 in miliseconds.

On powershell for instance this will be (([datetime]::UtcNow) - (get-date "1/1/1970")).TotalMilliseconds

I tried to use moment.js like :

A = moment.utc();
B = moment('19700101', 'YYYYMMDD')

console.log("A is ",A)
console.log("B is ",B)

console.log("A format is ", A.format())
console.log("B format is ", B.format())

console.log("Milisec diff : ", A.diff(B,'miliseconds'))

It returns

A is  h {_isAMomentObject: true, _useUTC: true, _isUTC: true, _l: undefined, _i: undefined, …}_d: Fri Nov 05 2021 10:43:43 GMT+0100 (heure normale d’Europe centrale) {}_f: undefined_i: undefined_isAMomentObject: true_isUTC: true_isValid: true_l: undefined_offset: 0_pf: {empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -2, charsLeftOver: 0, …}_strict: undefined_useUTC: true_z: null[[Prototype]]: Object

B is  h {_isAMomentObject: true, _i: '19700101', _f: 'YYYYMMDD', _l: undefined, _strict: undefined, …}_a: (7) [1970, 0, 1, 0, 0, 0, 0]_d: Thu Jan 01 1970 00:00:00 GMT+0100 (heure normale d’Europe centrale) {}_f: "YYYYMMDD"_i: "19700101"_isAMomentObject: true_isUTC: false_isValid: true_l: undefined_pf: {empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -1, charsLeftOver: 0, …}_strict: undefined[[Prototype]]: Object

A format is  2021-11-05T09:43:43+00:00
B format is  1970-01-01T00:00:00+01:00
Milisec diff :  1636109023628

So the diff is not the good one, it takes A with the local hours (10:43 for me) and not the UTC hours (9:43). It is probably because you have to consider A.format to see 9:43 but we cannot give A.format to diff function.

Thanks for your help !

Source: JavaSript – Stack Overflow

November 5, 2021
Category : News
Tags: gmt | javascript | momentjs | time | utc

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.