4

I was using the following code to calculate the age of a person:

var year = 1964;
var month = 1;
var day = 20;
var age = moment(year + '-' + month + '-' + date, 'YYYY-MM-DD').fromNow(true);

The problem with fromNow() is that it rounds the number up or down depending on the decimal point. I would like it to only round down. In the above example the person's real age is 51 but it's returning 52 because his age is actually something like 51.75.

If I use diff() instead it rounds down which is perfect. But it doesn't give me the pretty text 51 years old.

var age = moment().diff([year, month - 1, date], 'years');

My question is, is there a way to make fromNow() round down?

Ben Sinclair
  • 3,896
  • 7
  • 54
  • 94
  • [This answer](http://stackoverflow.com/questions/25323823/round-moment-js-object-time-to-nearest-30-minute-interval) might come in handy ;) – Edward J Beckett Jul 22 '15 at 07:22

2 Answers2

2

You can configure a custom rounding function:

moment.relativeTimeRounding(Math.floor)
levi
  • 23,693
  • 18
  • 59
  • 73
0

The provided solution is correct but I thought I'd add a little explanation as this was the first google result.

Say I have a scenario where I want dates that were 1m 30s ago to display a minute ago rather than two minutes ago:

const minuteAndAHalfAgo = new Date();
minuteAndAHalfAgo.setMinutes(minuteAndAHalfAgo.getMinutes() - 1);
minuteAndAHalfAgo.setSeconds(minuteAndAHalfAgo.getSeconds() - 30)

moment.relativeTimeRounding(Math.floor);
console.log(moment(minuteAndAHalfAgo).fromNow()); // a minute ago

the relativeTimeRounding function takes a function as an argument which in our case is Math.floor which means the relative time evaluation will be rounded down. This can be found in the docs https://momentjs.com/docs/#/customization/relative-time-rounding/ - you can also specify a relativeTimeThreshold — the point at which to round the number.

Luke Garrigan
  • 4,571
  • 1
  • 21
  • 29