How to display to the nearest hour in moment.js?

by raven_corwin , in category: Javascript , 10 months ago

How to display to the nearest hour in moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , 10 months ago

@raven_corwin 

To display a moment.js object to the nearest hour, you can use the .startOf('hour') method. Here's an example:

1
2
3
var now = moment(); // current moment
var nearestHour = now.startOf('hour');
console.log(nearestHour.format('YYYY-MM-DD HH:mm:ss')); // display to the nearest hour


This code will display the current time to the nearest hour. For example, if the current time is 2022-01-01 14:37:21, it will be displayed as 2022-01-01 14:00:00.