1

Short question: I need momentjs to humanize 60 minutes into 1 hour instead of an hour. Can't figure out how to get it to work.

Long question: Just started using momentjs, works great. We are using it to display how often a dashboard is updated.

The timers are set as a integer in minutes. We are using the humanize moment option to display 30 as 30 minutes and 360 as 6 hours etc.

This works great but not in 2 cases. 60 gets humanized to an hour. We need it to be 1 hour. And 1440 is displayed as a day, instead of 1 day.

We need this change because the column is answering the question "How often does your metric update?"

The answer is "every 1 hour". "every an hour" doesn't quite work.

I read through the docs and googled, but couldn't find a way to customize just a few humanized display formats.

We are already setting true as the second parameter to get just the value without the suffix from this question and answer - How to Customize Humanized Moment js Date Result

But the value comes back as 'an hour' instead of '1 hour'.

enter image description here

Community
  • 1
  • 1
Joshua Dance
  • 8,847
  • 4
  • 67
  • 72

2 Answers2

3

You can use updateLocale method documented in the Customize -> Relative time section of the docs. This will affect output of from, fromNow, to, toNow and humanize.

In your case you can simply update h and d keys of the relativeTime object.

Here a working sample:

moment.updateLocale('en', {
  relativeTime : {
    h: "1 hour",
    d:  "1 day",
  }
});

var d1 = moment.duration(60, 'm');
var d2 = moment.duration(1440, 'm');

console.log(d1.humanize());
console.log(d2.humanize());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

You can find further examples of relative time customization here and here.

Community
  • 1
  • 1
VincenzoC
  • 30,117
  • 12
  • 90
  • 112
0

you can use the methods like minutes(), months(), years() available on the duration object and then you can create your own string. the humanize() method gives an approximate value against the duration and not the exact duration.

Vineeth Sai
  • 3,389
  • 7
  • 23
  • 34
Ali Ameen
  • 1
  • 2