Relative Date in Moment.js using .fromNow() - how to get together years, months and days ago?
Asked Answered
L

2

7
  1. Let's say I have a date string 2015-02-01 - (1st Feb 2015)
  2. Today we have 2016-07-02 (2nd Jul 2016)

We can easily see that the older date took place approximately 1 year and 5 months and 1 day ago.

I wanted to achieve relative result like that using Moment.js, so I did:

return moment('2015-02-01').fromNow();

Unfortunately, library rounds the result and I get a year ago, where almost half of the next year is ignored (missing 5 months and 1 day).

The only available boolean argument passed to .fromNow() is nothing that can help. Is it possible to get full relative date where I could control breakdown even to hours, minutes and seconds if needed?

Lederman answered 2/7, 2016 at 9:58 Comment(0)
N
9

You have a couple options depending on what direction you want to go with this. Probably the most straightforward is to use a duration instead of .fromNow().

Just do:

var diff = moment('2015-02-01').diff(moment(), 'milliseconds');
var duration = moment.duration(diff);

This gets you a duration type in moment, which you can get lots of information from. For example:

duration.years(); //-1
duration.months(); //-4
duration.days();// -30
duration.hours(); //-8

Or if you want the units in aggregate:

duration.asYears(); //-1.416481451250425
duration.asMonths(); //-16.997784898617585

And so on. You can format this however you would like.

If you would like more advanced duration formatting you can check out this plugin.

Nace answered 2/7, 2016 at 14:45 Comment(0)
S
0

Maybe my small es-date-fiddler library is useful.

const $D = window.$D;
const now = $D();
const diff = $D(`2015-02-01`).differenceFrom(`2016-07-02`);
const diffFromNow = $D().differenceFrom(`2015/02/01`);

console.log(`2015-02-01 until 2016-07-02\n =>`, diff.clean);
console.log(`From 2015/02/01 to now =>`, diffFromNow);
.as-console-wrapper {
    max-height: 100% !important;
}
<script 
  src="https://kooiinc.github.io/es-date-fiddler/Bundle/index.browser.min.js">
</script>
Squeegee answered 31/1, 2024 at 11:25 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.