prithee
prithee

Reputation: 37

How to calculate relative date from now in only days using momentjs?

I am trying to get the amount of days relative to the current time, returning only days as units. So if something happened a week ago, it would say 7 days. If it happened 2 months ago, it would return that time in days as well.

I am aware of how to get there but I am having trouble putting the pieces together.

I have my days as a data attribute "data-order" so data-order="2019-4-2 00:00" or "2019-4-2" if it makes calculations easier.

$(".pop-cal").each(function (i, obj) {
    moment.relativeTimeThreshold("m", 1);
    moment.relativeTimeThreshold("d", 25 * 100);

    var date = $(this).attr("data-order");
    var momentDate = moment(date).fromNow();

    $(this).attr("data-content", momentDate);
});

This is getting me dates, but they are always off.

My expected results would be similar confirmation to using google search and saying "58 days ago" and getting Tuesday February 12th 2019.

What I am currently getting as result are "59 days ago" on a moment time created on "2019-2-12.

Upvotes: 3

Views: 3016

Answers (1)

sheilak
sheilak

Reputation: 5873

The fromNow method isn't suitable if you need the exact number of days, because it works by converting the time to a Duration (measured in months and milliseconds), and then converting the Duration to a human readable form (humanize method).

As the Duration docs state:

It is much better to use moment#diff for calculating days or years between two moments than to use Durations.

You can see the problem if you perform fromNow on February 28th and March 1st, 1 day apart but giving a fromNow of 4 days apart (due to 28 days in February instead of 31 days).

moment("2019-03-01").fromNow() // "45 days ago"
moment("2019-02-28").fromNow() // "49 days ago"

The moment#diff method can give you the exact difference between two moments in days, e.g. between moments a and b:

a.diff(b, 'days') 

Upvotes: 2

Related Questions