Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is moment().isValid() method in JavaScript?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

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.

Syntax

moment(datetime).isValid
Check if a date or time is valid using moment.js

Parameters

  • datetime: This is a date or time that we want to check if it is valid.

Return value

This method returns a Boolean value. If the date or time provided is correct, then a true is returned. Otherwise, a false is returned.

Code example

Let's look at the code below:

// require the moment module
const moment = require("moment")
// create some dates and time
const date1 = moment(); // current date and time
const 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 time
const 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 valid
console.log(date1.isValid()) // true
console.log(date2.isValid()) // true
console.log(date3.isValid()) // false
console.log(date4.isValid()) // true
console.log(date5.isValid()) // false
console.log(time1.isValid()) // false
console.log(time2.isValid()) // true
Check if Date or Time is Valid using moment.js

Code explanation:

  • Line 2: We require the moment package.
  • Lines 5 to 11: We create some dates and times. Some of them are valid, and some are invalid.
  • Lines 14 to 20: We use the isValid() method to check if the dates and times created are valid. Then we print the results to the console.

RELATED TAGS

javascript

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring