Is It Possible To Edit The Granularity Of The Moment#to Output?
With MomentJS's Moment#to method, is there any way that I can control the output at all? I'd like for now2.to(opens) to ignore seconds while comparing, so it would return 'in 17 m
Solution 1:
The official way to customize how moment displays relative time is using relativeTimeRounding
and relativeTimeThreshold
(and relativeTime
key of moment.updateLocale
if needed).
In your case, to get the desired output, you can set rounding function to Math.floor
(default Math.round
) and set second threshold to 60 (default 45).
Here a live sample:
var opens = moment('Tue 8:00:00am', 'ddd h:mm:ssa');
var now1 = moment('Tue 7:43:30am', 'ddd h:mm:ssa');
var now2 = moment('Tue 7:43:31am', 'ddd h:mm:ssa');
var now3 = moment('Tue 7:44:01am', 'ddd h:mm:ssa');
console.log(now1.to(opens)); // in 17 minutes
console.log(now2.to(opens)); // in 16 minutes
console.log(now3.to(opens)); // in 16 minutes
// Change relative time rounding
moment.relativeTimeRounding(Math.floor);
// Set 1 minute = 60 seconds (default 45)
moment.relativeTimeThreshold('s', 60);
console.log(now1.to(opens)); // in 16 minutes
console.log(now2.to(opens)); // in 16 minutes
console.log(now3.to(opens)); // in 15 minutes
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Solution 2:
you can achieve this by changing the transformation parser. If you don't pass seconds information, the .to method won't take them into account.
var opens = moment('Tue 8:00:00am', 'ddd h:mm')
var now1 = moment('Tue 7:43:30am', 'ddd h:mm')
console.log(now1.to(opens)) // in 17 minutes
var now2 = moment('Tue 7:43:31am', 'ddd h:mm')
console.log(now2.to(opens)) // in 17 minutes
Post a Comment for "Is It Possible To Edit The Granularity Of The Moment#to Output?"