5

I have a string with a german date (31.01.2019, DD.MM.YYYY). Now I need to check if the date is valid with date-fns.

dateFns.isValid(new Date('19.11.2019'), 'DD.MM.YYYY');

This is not working. I always get a false feedback from date-fns. I think date-fns is expecting another date format.

How can I validate the string with the german date format?

HansPeter
  • 319
  • 1
  • 4
  • 12
  • If you pass a string to `new Date` then it has to be in the ISO format, any other format either results in an invalid date or in an unpredictable result. And `19.11.2019` is not a valid string to create a Date. – t.niese Feb 02 '19 at 20:18
  • You can split it at every dot `.` and then use the `Date` constructor like this: https://stackoverflow.com/a/33299764 – adiga Feb 02 '19 at 20:20

2 Answers2

4

You can useisValid and parse functions of the date-fns library :

import { isValid, parse } from 'date-fns';

// parse the string to a Date
const date = parse('31.08.2012', 'dd.MM.yyyy', new Date());

// then check the validity of that date
isValid(date)

Check the documentation for more details on these functions : https://date-fns.org/docs/Getting-Started

Tkim
  • 350
  • 1
  • 8
  • could you help https://stackoverflow.com/questions/67760399/how-to-replicate-a-function-using-date-fns – Asking May 30 '21 at 11:23
0

From the date-fns the documentation :

Returns false if argument is Invalid Date and true otherwise. Invalid Date is a Date, whose time value is NaN.

Since new Date('19.11.2019') gives already an Invalid Date (since it is not ISO formatted) therefore you get false.

If you want to use german format you should convert your date format to the ISO one.

  • Thanks. date-fns supports only the format yyyy-mm-dd for validation? is this correct? – HansPeter Feb 02 '19 at 21:21
  • @HansPeter before version 2.x (which is still alpha), the `isValid` function only accepts a `Date` object as input, and checks if that `Date` object holds a valid date information. It does not do any validation of the format, only if it holds a valid date. And a javascript `Date` object does not hold any format, it just holds a representation of a date. And `new Date` only accepts dates in the ISO format. – t.niese Feb 03 '19 at 08:33