0

I am working on report generation module and I am checking if the value in each record a date for formatting purpose.

var records = [{
    recordNumber : "CNE-TEST-00056", 
    name : "Test Name 1",
    createdAt: "2018-03-12"
  }, {
    recordNumber : "CNE-TEST-00057", 
    name : "Test Name 2",
    createdAt: "2018-01-26T18:30:00.000Z"
  }];

These are the records in my report. The keys in each object will be dynamic and I want to know what type they are of actually.

I am trying to know type Date by using function below.

function isDate(date){
    var date1 = new Date(date);

    if(isNaN(date1.getFullYear()) || date1.getFullYear() == 1970){
        return false;
    }

    return true;
}

When I do new Date("CNE-TEST-00056") it should technically return me Invalid Date and new Date("CNE-TEST-00056").getFullYear() should return NaN. But it returns Sun Jan 01 1956 00:00:00 GMT+0530.

How can I make it say "CNE-TEST-00056" is not a date.

Abhijit Borade
  • 512
  • 4
  • 18
  • maybe upgrade to some better wrappers like moment.js – john Smith Jun 25 '18 at 16:38
  • @johnSmith But before formatting with moment.js I should know that the field I am using is a date. – Abhijit Borade Jun 25 '18 at 16:41
  • @johnSmith `moment("CNE-TEST-000056")._isValid` this gives me true. – Abhijit Borade Jun 25 '18 at 16:44
  • It's trying hard to get a date from your input and "year 1956" is the only assumption it's able to make. Using `Date()` constructor to parse dates from strings is unreliable and inconsistent (no matter how popular it is) but it's particularly useless to validate dates. – Álvaro González Jun 25 '18 at 17:25
  • If using the built-in parser, the only way to validate the date values is to also manually parse the string and compare the results (a library might help with that but it’s not necessary). – RobG Jun 26 '18 at 03:55

1 Answers1

0

For you specific example, you can use a little bit of a hacky way to determine it.

Code snippet -> https://snipp.ly/xo2ib7Bi

function isDate(date){
    var date1 = new Date(date);

    if(isNaN(date1.getFullYear()) || date1.getFullYear() == 1970 || date.replace(/[^A-Z]/gi, "").length > 2){
      return false;
    }

   return true;
 }

This adds an extra check to your if statement that replaces everything that isn't a alphabetic letter and gets the count. So when it does that for CNE-TEST-0057, the count is 7 while for 2018-01-26T18:30:00.000Z the count is 2 for 'T' and 'Z'. This isn't full proof as something like C-T-00057 would pass as true. I don't think there is a way to do this with javascript's Date parsing, I believe this requires an extra check on your data has I have showed in the example above

User9123
  • 734
  • 5
  • 7
  • Please post runnable snippets here, not elsewhere. Links rot. This also doesn’t seem to be a very good test. Is “July 23, 1970” an invalid date? – RobG Jun 26 '18 at 03:56