2015-02-01
- (1st Feb 2015)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?
add('years', 1). format('L') = "12/01/2012" ?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With