AmHilal
AmHilal

Reputation: 79

Why is local time not different from UTC in moment.js?

I have the following code that makes use of moment.js:

var Now = moment();
var UTC = moment().utc();

 if (moment().isBefore(UTC)){
    $("#was").html("Time difference : " + Now.from(UTC)).fadeIn('fast');
 } else {
    $("#was").html("Time difference : " + UTC.fromNow()).fadeIn('fast');
 }

Result is always: "A few seconds ago". Can you tell me what I am doing wrong?

Upvotes: 1

Views: 1885

Answers (1)

Oerd
Oerd

Reputation: 2303

Although Now and UTC will display differently, they are the same "moment in time". To understand this you have to grasp how moment.js works internally. Here is some info from the official moment.js documentation (emphasis mine):

By default, moment parses and displays in local time.

If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment().

So the difference is all in parsing and displaying. Internally, moment objects have the same timestamp. A little test to demonstrate this is to append (and run) the followin after your code:

console.log(Now.valueOf());
console.log(UTC.valueOf());
console.log(Now.valueOf() - UTC.valueOf());  // will be "a few secods" at most ;)

Update: If your intention was to create a moment of, say, 5 hours ago, then:

var hours_ago = 5;
var earlier = moment().subtract('hours', hours_ago); // 5 hours ago
var earlier_yet = moment().subtract({'days': 2, 'hours': 3}) // 2 days, 3 hours ago

Upvotes: 3

Related Questions