-1

I need to check whether given string is date or not. Note: Without using any library

I try to use this

if (!isNaN(str) || isNaN(Date.parse(str))) {
    console.log("Not a Date");
} else {
    console.log('It is Date');
}

It works in all scenarios except one, if the given input is Hello 2, it returns It is Date

So, is there any way with which I can appropriately validate my string against Date?

  • If you know what date format you want to get, you could work with regular expressions. Something like this: https://stackoverflow.com/questions/18758772/how-do-i-validate-a-date-in-this-format-yyyy-mm-dd-using-jquery/18759013 – Maik Lowrey Apr 09 '21 at 20:00

2 Answers2

1

Seems like your requirement is to validate the date which has year between 1000 - 9999, with validate day and month mapping.

Here is what you should be doing

  • store a variable by converting it to Date const myDate = new Date(your_date_string);
  • Then you should write logic to check if the time returned by date is valid number isNaN(myDate.getTime())
  • Then you should write logic to check if the year is within the range (you require) For eg: myDate.getFullYear() > 9999 || myDate.getFullYear() < 1000
  • Then you should check if the day and month processed is valid. For that you can get month and date by using myDate.getUTCMonth() & myDate.getUTCDate() accordingly. and check the mapping. Please note UTCMonth and UTCDate is index.
  • if all the above is valid then the date is valid else not. Somewhat like this
function isValidDate(myDate) {
  const d = new Date(myDate);
  if (Object.prototype.toString.call(d) === '[object Date]') {
    if (isNaN(d.getTime()) || d.getFullYear() > 9999 || d.getFullYear() < 1000 || !(your_date_mapping_logic)) {
      console.log('Invalid Date.');
    } else {
      console.log('Valid Date.');
    }
  }
}
Gaurav Mall
  • 500
  • 4
  • 16
0

Try with the below condition

if (isFinite(new Date(str).getTime())) {
    console.log("Not a Date");
} else {
    console.log('It is Date');
}
Wazeed
  • 1,230
  • 1
  • 8
  • 9