I try to parse the date from a string but I got invalid date.
Seems I doing something incorrect here but can't find out why. I give the string and the format to parse from. as I say I get invalid date.
How to do it correctly?
import dayjs from 'dayjs';
console.clear();
const i = '28-04-2021';
const b = dayjs(i, 'DD-MM-YYYY').toDate();
console.log({ b }); // output invalid date.
codesandbox.io
I try to parse the date from a string but I got invalid date.
Seems I doing something incorrect here but can't find out why. I give the string and the format to parse from. as I say I get invalid date.
How to do it correctly?
import dayjs from 'dayjs';
console.clear();
const i = '28-04-2021';
const b = dayjs(i, 'DD-MM-YYYY').toDate();
console.log({ b }); // output invalid date.
codesandbox.io
Share Improve this question asked May 8, 2021 at 8:47 Jon SudJon Sud 11.7k31 gold badges104 silver badges228 bronze badges 3- 2 How much research effort is expected of Stack Overflow users? – Andreas Commented May 8, 2021 at 8:59
-
well, I know I can use dayjs plugin. but even without the plugin I have a constructor that takes many overload. and in the one of the options I have
ctor(string, format)
. so I ask because seems the dayjs have built in without the plugin. this is very confuse me. – Jon Sud Commented May 9, 2021 at 4:47 - Docs -> Parse -> String + Format: "This dependent on CustomParseFormat plugin to work" - right at the top, in a highlighted yellow box... – Andreas Commented May 9, 2021 at 9:33
1 Answer
Reset to default 7According to doc you are missing this lines of code
import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat);
then you can use this type of constructor dayjs(date, format)
.
to use it globally, i would remend to put it at the top of the project. In your example, put it right after import of dayjs
.