I have following custom javascript function to get duration in days/hours/minutes -
daysFromNow(time) {
let oldThreshold = <number>Moment.relativeTimeThreshold('d');
try {
Moment.relativeTimeThreshold('m', 60);
Moment.relativeTimeThreshold('h', 24);
Moment.relativeTimeThreshold('d', 999999);
return Moment(time).fromNow();
} finally {
Moment.relativeTimeThreshold('d', oldThreshold);
}
}
Now
console.log(daysFromNow('2024-01-11T23:59:59.000+10:30')); // gives 'in 29 days'
console.log(daysFromNow('2024-01-12T23:59:59.000+10:30')); // gives 'in 30 days'
console.log(daysFromNow('2024-01-13T23:59:59.000+10:30')); // gives 'in 30 days', should be 31
console.log(daysFromNow('2024-01-14T15:10:59.000+10:30')) // gives 'in 31 days' - should be 32
Not sure where I did the wrong. Is that something about timezone?
For your specific case, I would suggest using the
startOf()
method to normalize the time to the start of the day and then comparing the difference.NOTE: There are other alternatives of using
momentjs
library which is recommended by themomentjs
docs itself. For your specific case, I would be tilted to useIntl
object which is natively introduced in Javascript. So, you might want to take a look at this as well.