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.
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 thatmm (lowercase)
represents minutes, like00, 01, ..., 59
andMM (capitalized)
represents months like01, 02, ..., 12
.Parsing with the correct format string works, see snippet below: