Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive a string and verify if it is a valid date with date-fns

I just want to validate if the string that i received is a valid date using date-fns. I gonna receive a date like this '29/10/1989', BR date. I want to transform it into 29-10-1989 and check if its valid. Anyone can help me with this?

const parsedDate = parseISO('29/10/1989')

this code above doesnt work, i got 'Invalid Date'

like image 604
Rafael de Carvalho Avatar asked Feb 05 '21 17:02

Rafael de Carvalho


People also ask

Is valid date string date-fns?

Date-fns provides you with date validation helpers with the isValid() function that checks if a given date is valid. By default, date-fns returns a Boolean variable true if the date parsed is indeed a valid date or false if the date string parsed is not a valid date.

How do you validate if a string is a date?

parse() method is employed to parse the date string. The method inputs the date as an argument and returns the milliseconds. Moreover, you can use regular expressions to validate a date as well. The expression checks that the user entered the date by following the “mm/dd/yy” format.

How do you check if a string is a valid date in python?

Method #1 : Using strptime() In this, the function, strptime usually used for conversion of string date to datetime object, is used as when it doesn't match the format or date, raises the ValueError, and hence can be used to compute for validity.


1 Answers

Try parse with locale options like this:

import { parse, isValid, format } from 'date-fns';
import { enGB } from 'date-fns/locale';

const parsedDate = parse('29/10/1989', 'P', new Date(), { locale: enGB });
const isValidDate = isValid(parsedDate);
const formattedDate = format(parsedDate, 'dd-MM-yyyy');
like image 97
Anatoly Avatar answered Sep 18 '22 22:09

Anatoly