The add()
method in moment.js
adds time to a particular time. We can add more days, more hours, more weeks, more months, and so on.
Here is the syntax for the add()
method:
time.add(number, shorthand)
time
: This is the time before adding the additional time.
number
: This represents the number of the time unit we want to add. It could be 7, 3, or more.
string
: This represents the kind of time we want to add. It could be months, seconds, and so on. For example, we can use "y" or years, "M" or months, and so on.
It returns a new time with more time added to it.
// require the moment moduleconst moment = require("moment")// create some dates and timeconst time1 = moment([2010, 1, 14, 10, 25, 50, 125])const time2 = moment(new Date) // current date and timeconst time3 = moment(1318781876406)const time4 = moment({hour: 20, minute: 20, second: 34})console.log("before adding more time")// get the hour of the timeconsole.log(time1.format("DD MM YYYY hh:mm:ss")) // 10console.log(time2.format("DD MM YYYY hh:mm:ss")) // 15console.log(time3.format("DD MM YYYY hh:mm:ss")) // 16console.log(time4.format("DD MM YYYY hh:mm:ss")) // 20// add more timetime1.add(2, "days")time2.add(20, "h")time3.add(12, "minutes")time4.add(4, "Y")console.log("After adding more hour")// get the hour of the time againconsole.log(time1.format("DD MM YYYY hh:mm:ss"))console.log(time2.format("DD MM YYYY hh:mm:ss"))console.log(time3.format("DD MM YYYY hh:mm:ss"))console.log(time4.format("DD MM YYYY hh:mm:ss"))