How to Set Hours with Moment.js in JavaScript?

Estimated read time 2 min read

Moment.js is a popular JavaScript library for working with dates and times. To set hours using Moment.js, you can use the hour() method to set the hour component of a moment object to a specific value. Here’s an example code snippet that demonstrates how to set hours with Moment.js:

const momentObj = moment(); // create a new moment object representing the current date and time
momentObj.hour(9); // set the hour component to 9
console.log(momentObj.format()); // output the moment object in ISO 8601 format

In this code, the moment() function is used to create a new moment object representing the current date and time. The hour() method is then called on the moment object to set the hour component to 9. Finally, the format() method is called on the moment object to output it in ISO 8601 format, which includes the date and time components in a standardized format.

You can replace the value passed to the hour() method with any integer value between 0 and 23 to set the hour component to a specific value. For example:

momentObj.hour(16); // set the hour component to 4 PM

You can also use the moment() function to create a moment object representing a specific date and time, and then use the hour() method to set the hour component of that moment object. For example:

const momentObj = moment("2022-07-01T09:00:00"); // create a new moment object representing July 1, 2022 at 9:00 AM
momentObj.hour(14); // set the hour component to 2 PM
console.log(momentObj.format()); // output the moment object in ISO 8601 format

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply