Maddy
Maddy

Reputation: 2060

diff momentjs days vs milliseconds yields different results

In my code I have the following

const today = moment();
const someday = moment('Wed Oct 10 2018 13:50:00 GMT-0400 (Eastern Daylight Time)');

const diff = today.diff(someday, "days");
const diff2 = today.diff(someday);
out.innerText = diff;
out2.innerText = moment.utc(diff2 * 1000).format("D[ day(s)] H[ hour(s)] m[ minute(s)]");

I am expecting diff and diff2 to have same days but diff returns correct date where as diff2 returns the incorrect data. How does formatting here make a difference?

JSFiddle : link

Upvotes: 0

Views: 77

Answers (2)

thmsdnnr
thmsdnnr

Reputation: 1302

Try:

out2.innerText = moment.duration(diff2).asDays();

This will give you the decimal number of days (without the utc conversion) -- and this matches what you're seeing with today.diff(someday, "days").

You could format it yourself in the desired X day(s) Y hour(s) Z minute(s) fashion like this:

const theDuration = moment.duration(diff2);
out2.innerText = Math.floor(theDuration.asDays()) + " day(s) " + 
  theDuration.hours() + " hour(s) " + theDuration.minutes() + " minute(s)";

Just make sure the time zones are all matched up between your input date format / the clock on the machine you're calculating on / the desired user output. This is a useful overview on the docs page: local / utc.

I've also seen the moment-duration-format library mentioned as useful: https://github.com/jsmreese/moment-duration-format

Try:

out2.innerText = moment.utc(diff2).format("DDDD [ day(s)] H[ hour(s)] m[ minute(s)]");

Using "Day of year" (DDDD) instead of "Day of month" (DD) in the format string (moment.js .format docs), and removing the unnecessary * 1000 in the .utc constructor, since like Jb31 mentioned, diff2 is already in milliseconds. Per Jb31, this is a quite awful idea when the days in the diff hits 365...

Upvotes: 1

Jb31
Jb31

Reputation: 1391

today.diff(someday) returns the difference between the two days in milliseconds when no second parameter is given (like 'days'). In out2 you attempt to interpret this as a unix timestamp. This is wrong for two reasons:

  • You don't need to multiply the difference with 1000, it's in milliseconds already.
  • Even if you didn't do the multiply, the statement seems pointless as moment.utc(diff2) will point to 1970-10-06 (seen from today). The format command will then return the days, hours and minutes part of this date.

Upvotes: 0

Related Questions