[javascript] Check if date is a valid one

Following is the scenario:

I have a String date and a date format which is different. Ex.:
date: 2016-10-19
dateFormat: "DD-MM-YYYY".

I need to check if this date is a valid date.

I have tried following things

var d = moment("2016-10-19",dateFormat);

d.isValid() is returning false every time. Does not Moment.js parse the date in the given format?

Then I tried to format the date in DD-MM-YYYY first and then pass it to Moment.js:

var d = moment("2016-10-19").format(dateFormat);
var date = moment(d, dateFormat);

Now date.isValid() is giving me the desired result, but here the Moment.js date object is created twice. How can I avoid this? Is there a better solution?

FYI I am not allowed to change the dateFormat.

This question is related to javascript date datetime momentjs

The answer is


I use moment along with new Date to handle cases of undefined data values:

const date = moment(new Date("2016-10-19"));

because of: moment(undefined).isValid() == true

where as the better way: moment(new Date(undefined)).isValid() == false


console.log(` moment('2019-09-01', 'YYYY-MM-DD').isValid()?  ` +moment('2019-09-01', 'YYYY-MM-DD').isValid())
console.log(` moment('2019-22-01', 'YYYY-DD-MM').isValid()?  ` +moment('2019-22-01', 'YYYY-DD-MM').isValid())
console.log(` moment('2019-22-22', 'YYYY-DD-MM').isValid()?  ` +moment('2019-22-22', 'YYYY-DD-MM').isValid())
console.log(` moment('undefined', 'YYYY-DD-MM').isValid()?  ` +moment('undefined', 'YYYY-DD-MM').isValid())

 moment('2019-09-01', 'YYYY-MM-DD').isValid()?  true
 moment('2019-22-01', 'YYYY-DD-MM').isValid()?  true
 moment('2019-22-22', 'YYYY-DD-MM').isValid()?  false
 moment('undefined', 'YYYY-DD-MM').isValid()?  false

How to check if a string is a valid date using Moment, when the date and date format are different

Sorry, but did any of the given solutions on this thread actually answer the question that was asked?

I have a String date and a date format which is different. Ex.: date: 2016-10-19 dateFormat: "DD-MM-YYYY". I need to check if this date is a valid date.

The following works for me...

const date = '2016-10-19';
const dateFormat = 'DD-MM-YYYY';
const toDateFormat = moment(new Date(date)).format(dateFormat);
moment(toDateFormat, dateFormat, true).isValid();

// Note: `new Date()` circumvents the warning that
// Moment throws (https://momentjs.com/guides/#/warnings/js-date/),
// but may not be optimal.

But honestly, don't understand why moment.isDate()(as documented) only accepts an object. Should also support a string in my opinion.


Try this one. It is not nice but it will work as long as the input is constant format from your date picker.

It is badDate coming from your picker in this example

https://jsfiddle.net/xs8tvox9/

var dateFormat = 'DD-MM-YYYY'
var badDate = "2016-10-19";

var splittedDate = badDate.split('-');

if (splittedDate.length == 3) {
  var d = moment(splittedDate[2]+"-"+splittedDate[1]+"-"+splittedDate[0], dateFormat);
  alert(d.isValid())
} else {
  //incorrectFormat
}

Here you go: Working Fidddle

$(function(){
  var dateFormat = 'DD-MM-YYYY';
  alert(moment(moment("2012-10-19").format(dateFormat),dateFormat,true).isValid());
});

If the date is valid then the getTime() will always be equal to itself.

var date = new Date('2019-12-12');
if(date.getTime() - date.getTime() === 0) {
    console.log('Date is valid');
} else {
    console.log('Date is invalid');
}

I just found a really messed up case.

moment('Decimal128', 'YYYY-MM-DD').isValid() // true

var date = moment('2016-10-19', 'DD-MM-YYYY', true);

You should add a third argument when invoking moment that enforces strict parsing. Here is the relevant portion of the moment documentation http://momentjs.com/docs/#/parsing/string-format/ It is near the end of the section.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to momentjs

How to get am pm from the date time string using moment js Vuejs and Vue.set(), update array How to subtract one month using moment.js? Get timezone from users browser using moment(timezone).js Check if date is a valid one moment.js get current time in milliseconds? Deprecation warning in Moment.js - Not in a recognized ISO format Moment js get first and last day of current month Moment get current date Moment.js - How to convert date string into date?