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

3

32

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'

Crock answered 5/2, 2021 at 17:49 Comment(0)
I
53

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');
Interpretative answered 5/2, 2021 at 18:17 Comment(0)
J
4

I came up with this (based on Anatoly answer):

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

function isValidDate(day, month, year) {
  const parsed = parse(`${day}/${month}/${year}`, 'P', new Date(), { locale: enGB })
  return isValid(parsed)
}

console.log(isValidDate('31', '04', '2021')); // invalid: april has only 30 days
console.log(isValidDate('30', '04', '2021')); // valid
Jamie answered 18/5, 2021 at 18:56 Comment(0)
G
1

I'm phasing a similar problem and I think this also solves it. I prefer this solution as the parsing is a bit more explicit than the locale object.

import { parse, isValid, format } from "date-fns";

const getFormmatedDate = (date) => {
  const parsed = parse(date, "dd/MM/yyyy", new Date());
  if (isValid(parsed)) {
    return format(parsed, "dd-MM-yyyy");
  }
  return null;
};

console.log(getFormmatedDate("31/04/1989")); // invalid: april has only 30 days
console.log(getFormmatedDate("30/04/1989"));

Gonsalez answered 30/5, 2023 at 19:2 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.