How to add "hours" and "minutes" words with moment.js?

by lindsey.homenick , in category: Javascript , 10 months ago

How to add "hours" and "minutes" words with moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 8 months ago

@lindsey.homenick 

To add "hours" and "minutes" words with moment.js, you can use the .add() and .subtract() methods provided by the library.


Here is an example of how you can add "hours" and "minutes" words to a moment object:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Assuming you have already included the moment.js library
// Create a moment object with a specific date and time
var myMoment = moment("2022-01-01 12:30");

// Add 2 hours and 15 minutes to the moment object
myMoment.add(2, 'hours');
myMoment.add(15, 'minutes');

// Get the updated hours and minutes as separate values
var hours = myMoment.hours();
var minutes = myMoment.minutes();

// Output the result with "hours" and "minutes" words
console.log(hours + ' hours ' + minutes + ' minutes'); // Output: 2 hours 15 minutes


In the code above, we create a moment object and use the .add() method to add hours and minutes. We then use the .hours() and .minutes() methods to get the updated values separately.


Finally, we can output the result with the "hours" and "minutes" words concatenated using string concatenation (+) and log it to the console.