0

I was trying to check if a string is valid date string or not with below code

const isValidDate = (date: any) => {
 return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));
}

For example :

let dateStr = "some-random-string-09"
console.log(isValidDate(dateStr)) // returns true instead of false

But if I remove the 09 from the string or add some text at the end of the string it returns the expected result.

for Ex:

let dateStr = "some-random-string"
console.log(isValidDate(dateStr)) // returns false as expected

it is really strange behaviour. Is there a way to validate this particular type of string in TypeScript?

zer00ne
  • 41,936
  • 6
  • 41
  • 68
spratap124
  • 151
  • 2
  • 10
  • 3
    Besides the ISO8601, what `Date` will accept as input is implementation dependent. Use [tag:regex] to validate input yourself. – Amadan Jul 27 '22 at 05:34
  • 1
    @Amadan—there are two other formats formally supported [*Date.parse*](https://262.ecma-international.org/#sec-date.parse): the formats of *Date.prototype.toString* and *Date.prototype.toUTCString*. – RobG Jul 27 '22 at 08:36
  • 1
    `new Date(date) !== "Invalid Date")` will always return *true* since the *Date* constructor always returns a *Date* object, which is always `!==` to a string. OTOH, `new Date(date) != "Invalid Date")` might return *true* or *false*, but is not a reliable way to determine whether a timestamp is valid. – RobG Jul 27 '22 at 08:53

1 Answers1

-1

You can achieve things like below code:

const incorrectDate = Date.parse('01 Jan 1970 00:00:00 GMT 09');
const CorrectDate = Date.parse('04 Dec 1995 00:12:00 GMT');

console.log(incorrectDate );
// expected output: NaN

console.log(CorrectDate );
// expected output: 818035920000

So if output is NaN then you can write your business logic

Sachin Padha
  • 211
  • 1
  • 4
  • what about `some-random-string-09` ? because backend is sending something like this. – spratap124 Jul 27 '22 at 05:22
  • if input always contain "-" then you break the string with "-" and check each character. – Sachin Padha Jul 27 '22 at 05:37
  • 1
    ["Parsing of strings with `Date.parse` is strongly discouraged due to browser differences and inconsistencies."](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#:~:text=Parsing%20of%20strings%20with%20Date.parse%20is%20strongly%20discouraged) – jsejcksn Jul 27 '22 at 05:37
  • Neither example format is supported by ECMA-262, so parsing is entirely implementation dependent and may or may not produce the stated results. – RobG Jul 27 '22 at 08:59