I am trying to format ISO dates with date-fns in Vue:
2022-01-13T14:06:33.612Z
1988-06-22T08:03:20.098Z
2021-12-03T14:50:34.060Z
to format them into 13.01.2022. There are some cases (say 10 entries) where I received the following formats:
1999-Dec-26
or
Wed Jan 05 2022 22:15:22 GMT+0100 (Central European Standard Time)
Also sometimes returns:
[Vue warn]: Error in v-on handler: "RangeError: Invalid time value"
I'm surprised that date-fns https://date-fns.org/docs/Getting-Started has no method to detect formats. Any suggestions? Thanks in advance!
convertIso (date) {
if (date !== "") {
date = new Date(date);
if (isValid(date) === true) {
return format(date, "dd.MM.yyyy"); // 2022-01-13T14:06:33.612Z
} else {
if (isDate(date)) {
const parseDate = parse(date, "yyyy-MMM-dd", new Date()); // 1999-Dec-26
const formatDate = format(parseDate, "dd.MM.yyyy");
// sometimes returns [Vue warn]: Error in v-on handler: "RangeError: Invalid time value"
return formatDate;
} else {
return "";
}
}
}
}
or
convertIso (date) {
if (date !== "") {
if (isValid(new Date(date)) === true)
return format(new Date(date), "dd.MM.yyyy"); // 2022-01-13T14:06:33.612Z
} else {
if (isDate(date)) {
const parseDate = parse(date, "yyyy-MMM-dd", new Date()); // 1999-Dec-26
const formatDate = format(parseDate, "dd.MM.yyyy");
// sometimes returns [Vue warn]: Error in v-on handler: "RangeError: Invalid time value"
return formatDate;
} else {
return "";
}
}
}
}
Yeah working with dates is such a mess in JS. Anyway, let's tackle the problem bit by bit.
In the lines below it seems that the lib is not doing any actual formatting I guess for some reason it's failing to read the date param as date so I'd suggest that you parse it first similar to what you're doing in the second if statement
if (isValid(date) === true) {
return format(date, "dd.MM.yyyy"); // 2022-01-13T14:06:33.612Z
}
Like this. But consider changed the format from 'MMM' to 'MM' to get 12 instead of Dec
if (isDate(date)) {
const parseDate = parse(date, "yyyy-MMM-dd", new Date()); // 1999-Dec-26
const formatDate = format(parseDate, "dd.MM.yyyy"); // sometimes returns [Vue warn]: Error in v-on handler: "RangeError: Invalid time value"
return formatDate;
}
That would get your dates in the right format that you want (13.01.2022) but it won't fix the Vue's error "RangeError: Invalid time value" because your format is simply a date, not a DateTime. You might consider extending your date pattern "dd.MM.yyyy" to be something like "dd-MM-yyyy'T'HH:mm:ss.SSSxxx" to include the time.
of course, you don't have to follow my example exactly, you don't have to use the 'T'. Tweak as you like. Just make sure that Vue can find some time value to read.
Finally, I just wanna say that I didn't use this lib before so if I kinda took a shot in the dark in here. If I missed something please let me know.
Also If you're not too invested may I suggest that you use day.js? I use it in such cases and it gives a pleasant experience every time I use it.