skip to Main Content

I have a table of data that needs to be sorted and in order to do so, I have to determine the datatype of the columns: numeric, text, or date. And no, I never know what the datatype of column will be and it will always have different data. I have to extrapolate the datatype by looking at the textcontent of the cell. The one I’m having an issue with is the date.

new Date("MOD-001-01") actually returns a real date of 1/1/2001.
new Date("This is not a date 1") also returns a real date, again 1/1/2001.

Is there any way to reliably test a value to see if its a date?

2

Answers


  1. Creating a date object by using the method referenced: new Date() accepts valid date string variations by parsing the string for numeric values, so in your example is essentially using the value 1 as the date.

    This will happen as long as there is at least one number. Using methods such as Date.parse() as mentioned in another comment will also give you unix value based on the parsed numeric value.

    An effective method of checking for valid dates would by using a regex expression on the string.

    There are various effective solutions here -> Regex to validate date formats

    Login or Signup to reply.
  2. To reliably test if a value is a date in JavaScript, you can use the Date.parse() method. The Date.parse() method attempts to parse a date string and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. If the date string is not valid, it will return NaN.

    You can use the following function to check if a value is a valid date:

    function isDate(value) {
      const timestamp = Date.parse(value);
      return !isNaN(timestamp);
    }
    

    Now you can use the isDate() function to check if a value is a date. It will return true if the value is a valid date, and false otherwise.

    Here are some examples:

    console.log(isDate("MOD-001-01"));  // false
    console.log(isDate("This is not a date 1"));  // false
    console.log(isDate("2023-07-11"));  // true
    console.log(isDate("July 11, 2023"));  // true
    

    By using Date.parse(), you can reliably determine if a value is a date or not.

    or else

    You can use a regular expression to check if a value is a date.

    You can use a library like Moment.js to parse and manipulate dates. These libraries provide more robust date parsing and manipulation capabilities than the built-in Date object.

    pls upvote if you find this helpful

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search