How to convert dd/mm/yyyy string into JavaScript Date object using date-fns?

86 Views Asked by At

I am converting dd/mm/yyyy string into JavaScript Date object. My code is working but is there any better way to do it by using date-fns? My current solution is:

calculateDate(value: string>): Date {
    const dateParts = value?.split('/');
    const calcualtedDate = value && new Date(dateParts[2] + '/' + dateParts[1] + '/' + dateParts[0]);
    return calcualtedDate;
  }

I tried date-fns parse but it return Invalid date.

1

There are 1 best solutions below

0
On

Check out the docs, most notably the docs on parse, and look at the table which describes the formatting string.

If you're using the format string that you use in your question (dd/mm/yyyy) you'll notice that mm (lowercase) represents minutes, like 00, 01, ..., 59 and MM (capitalized) represents months like 01, 02, ..., 12.

Parsing with the correct format string works, see snippet below:

console.log(parse('24/10/2023', 'dd/MM/yyyy', new Date()));
<script type="module">
  import { parse } from 'https://cdn.jsdelivr.net/npm/[email protected]/+esm'
  
  window.parse = parse;
</script>