Check if date is a valid one
Asked Answered
T

12

210

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.

Twocolor answered 19/10, 2016 at 6:26 Comment(5)
Are you not allowed to change the value of dateFormat? In that case, you will have to change the format of the input, since 2016-10-19 is YYYY-MM-DD, not DD-MM-YYYY. What are you allowed to change?Remittance
The input is coming from date picker. Can't change that too :(Twocolor
May I ask why you are not allowed to change the dateFormat variable? var d = moment("19-10-2016", "DD-MM-YYYY"); would solve your problems as far as I'm concernedRemittance
really can't say. But that is not in my control to change that value.Twocolor
Possible duplicate of How to test a string is valid date or not using moment?Waxen
T
274

Was able to find the solution. Since the date I am getting is in ISO format, only providing date to moment will validate it, no need to pass the dateFormat.

var date = moment("2016-10-19");

And then date.isValid() gives desired result.

Twocolor answered 19/10, 2016 at 12:35 Comment(10)
Does anyone know what the current preferred method is now? This method now throws the following "Deprecation Warning": moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to github.com/moment/moment/issues/1407 for more info.Salts
@Salts Please look at #23263880, github.com/moment/moment/issues/2535Twocolor
Just a heads up that this doesn't always work: var a = moment('12345'); a.isValid() // is true This fails because moment will fall back to the default date object if it can't parse the date. And the default date object will always return a date (just not the one you want.)Irinairis
That Github thread, the first comments outlines why it's deprecated but doesn't provide an alternative for checking invalid dates. When using moment('1234').isValid() as documented it still throws a deprecation notice.Benevolent
need to add that moment('02').isValid() === true, so you might want to be careful with thatFullmer
Also moment('abcde 1').isValid() === trueSwale
Warning: isValid() is not in any way reliable without a format. Do not be burntMegan
This is a wrong answer because I always get true whatever string I pass inTum
var date = moment("2016-10-32") this is not valid date but it is returning date is validThickening
Also moment(undefined).isValid() === true (?)Nosh
S
168

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.

Salts answered 8/12, 2017 at 17:39 Comment(4)
This has no effect.Tum
this answer should be the correct answer........@Begueradj this has effect, try using different values, sometimes correct and sometimes wrongHudgens
And you can read about strict parsing hereEwer
This will let you enter 0000 as a yearHemorrhoidectomy
P
50

I just found a really messed up case.

moment('Decimal128', 'YYYY-MM-DD').isValid() // true
Phototransistor answered 9/7, 2019 at 4:35 Comment(2)
moment('Decimal128', 'YYYY-MM-DD', true).isValid() // false. Use strict mode :) momentjs.com/guides/#/parsing/strict-modeHunkydory
Strict mode works. Weird that this has to be strict though.Phototransistor
A
24

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 I: `new Date()` circumvents the warning that
//   Moment throws (https://momentjs.com/guides/#/warnings/js-date/),
//   but may not be optimal.

// Note II: passing `true` as third argument to `moment()` enables strict-mode
//   https://momentjs.com/guides/#/parsing/strict-mode/

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

Agreeable answered 9/10, 2019 at 17:31 Comment(1)
if we pass true as 3rd argument for moment, it check's for exact date format.Milker
D
22

Here you go: Working Fidddle

$(function(){
  var dateFormat = 'DD-MM-YYYY';
  alert(moment(moment("2012-10-19").format(dateFormat),dateFormat,true).isValid());
});
Devitrify answered 19/10, 2016 at 6:46 Comment(13)
Like I said the dateFormat is 'DD-MM-YYYY' and I am not allowed to change it.Twocolor
Oh i see. Let me see on that.Devitrify
Is it allowed to change the date string here 2016-10-19?Devitrify
Nope. That is coming from date pickerTwocolor
Can't you modify it after it comes from datepicker and before you input it to var d = moment("2016-10-19",dateFormat);?Devitrify
That is what I did in the second solution that I mentioned in description but that results in creating two moment objects which I want to avoid.Twocolor
@Twocolor You don't have to modify dateFormat or dateString.Devitrify
It outputs true but it should output false. Plus whatever I write, it gives random resultsTum
If I change the date to 25/25/2020 your solution returns true.Underworld
check with "2012-10-32" it will show date is valid but it is not a valid date.Thickening
@Underworld after changing date, did you click Run button on Upper Left corner of the fiddle to reload the changes?Devitrify
@devverma Pl. check my comment aboveDevitrify
@BillalBegueradj Pl. check my commentDevitrify
P
19

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

Priority answered 16/1, 2019 at 23:18 Comment(1)
moment(new Date('Decimal128')).isValid() // trueConditioned
P
8
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
Puente answered 21/5, 2019 at 6:47 Comment(1)
could you please add some explanation to your answer? What additional value does this add to the already existing and accepted answer?Tropical
A
7

What I have used is moment.js

let value = '19-05-1994';
let check = moment(value,'DD-MM-YYYY', true).isValid();
        console.log(check) //returns true
        return check
Amiamiable answered 11/12, 2021 at 9:14 Comment(0)
L
4

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');
}
Licht answered 12/7, 2020 at 4:31 Comment(0)
L
1

You can use

var d = moment("2016-10-19",dateFormat);
if(!isNaN(d)) {
  // d is a valid date.
}
Larrup answered 27/8, 2021 at 7:59 Comment(0)
U
1
moment("2022-10-18 04:00 AM", "YYYY-MM-DD HH:mm AM", true).isValid()
Urbani answered 19/10, 2022 at 19:19 Comment(0)
R
-3

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
}
Remittance answered 19/10, 2016 at 6:57 Comment(1)
Please, don't do this.Igorot

© 2022 - 2024 — McMap. All rights reserved.