user7597670
user7597670

Reputation:

moment update time from now string display

I am using moment and using the fromNow() method.

moment.updateLocale("en", {
  relativeTime: {
    s: "seconds",
    m: "a minute",
    mm: "%d minutes",
    h: "an hour",
    hh: "%d hours",
    d: "a day",
    dd: "%d days",
    M: "a month",
    MM: "%d months",
    y: "a year",
    yy: "%d years"
  }
});


let value = "2017-09-29T10:50:00.000000+0100";
let dateDisplay = moment(value).fromNow();
//this logs in an hour although it is in 50 mins
console.log(dateDisplay);

I believe that this is expected as in the docs on the link provided from above it states that 45 - 89 mins will show an hour ago.

Does anyone know how to update this so that it will work on actual time - i.e. 50 minutes ago/in 50 minutes? (depending on whether the time has passed or is in the future)

Upvotes: 1

Views: 537

Answers (1)

VincenzoC
VincenzoC

Reputation: 31482

You can use relativeTimeThreshold

As the docs says:

duration.humanize has thresholds which define when a unit is considered a minute, an hour and so on. For example, by default more than 45 seconds is considered a minute, more than 22 hours is considered a day and so on. To change those cutoffs use moment.relativeTimeThreshold(unit, limit) where unit is one of s, m, h, d, M.

In your case, you can use moment.relativeTimeThreshold('m', 60);. Here a live sample:

let value = "2017-09-29T11:00:00.000000+0100";
let dateDisplay = moment(value).fromNow();
console.log(dateDisplay);

moment.updateLocale("en", {
  relativeTime: {
    s: "seconds",
    m: "a minute",
    mm: "%d minutes",
    h: "an hour",
    hh: "%d hours",
    d: "a day",
    dd: "%d days",
    M: "a month",
    MM: "%d months",
    y: "a year",
    yy: "%d years"
  }
});

moment.relativeTimeThreshold('m', 60);

dateDisplay = moment(value).fromNow();
//this logs in an hour although it is in 50 mins
console.log(dateDisplay);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Upvotes: 1

Related Questions