Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  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?

like image 816
Matt Komarnicki Avatar asked Jul 02 '16 09:07

Matt Komarnicki


People also ask

How do you add years to a date moment?

add('years', 1). format('L') = "12/01/2012" ?

How do you find the month from a date with a moment?

month() method is used to get or set the month of the Moment object. The months in Moment. js are zero-indexed, therefore the range of the months is 0 to 11, with 0 being January and 11 being December. A value higher than 11 would make it bubble up to the next year.

How can I get previous date in moment?

Just like this: moment(). subtract(1, 'days') . It will give you the previous day with the same exact current time that is on your local pc. Save this answer.

How do you find moment with time and date?

js parsing date and time. We can parse a string representation of date and time by passing the date and time format to the moment function. const moment = require('moment'); let day = "03/04/2008"; let parsed = moment(day, "DD/MM/YYYY"); console.


1 Answers

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.

like image 124
Maggie Pint Avatar answered Sep 29 '22 00:09

Maggie Pint