In JavaScript, the moment.js
package or module provides us the ability to manipulate dates and times easily. This package has an isValid
method that allows us to check if a date or time is valid.
moment(datetime).isValid
datetime
: This is a date or time that we want to check if it is valid.This method returns a Boolean value. If the date or time provided is correct, then a true
is returned. Otherwise, a false
is returned.
Let's look at the code below:
// require the moment moduleconst moment = require("moment")// create some dates and timeconst date1 = moment(); // current date and timeconst date2 = moment('2020.01.01', 'YYYY.MM.DD')const date3 = moment([2010, 1, 14, 15, 25000, 5000, 125])const date4 = moment(new Date) // current date and timeconst date5 = moment([2015, 25, 35])const time1 = moment(13187818764064345345)const time2 = moment({hour: 20, minute: 20, second: 34})// check if the dates and time are validconsole.log(date1.isValid()) // trueconsole.log(date2.isValid()) // trueconsole.log(date3.isValid()) // falseconsole.log(date4.isValid()) // trueconsole.log(date5.isValid()) // falseconsole.log(time1.isValid()) // falseconsole.log(time2.isValid()) // true
moment
package.isValid()
method to check if the dates and times created are valid. Then we print the results to the console.