Date strings with fractions of a second marked as invalid when formatting #2596
-
I'm trying move away from using moment.js and as I'm trying to format some dates that are in my system, date-fns tells me that the dates are of an invalid format. I have a function that I use to format dates which looks as follows: import { format } from "date-fns";
export function formatDateTime(date) {
if (date) return format(date, "yyyy-MM-dd HH:mm:ss");
} When trying to format this date string It handles If I use Is there something I'm missing? Thanks. Edit: import { format } from "date-fns";
export function formatDateTime(date) {
if (date) return format(new Date(date), "yyyy-MM-dd HH:mm:ss");
} Creating a new Date object seems to work, but I'm not sure why just passing the string throws an error. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Careful using strings in the Date constructor, it is discouraged by MDN because the implementation varies with each runtime. |
Beta Was this translation helpful? Give feedback.
format
only accepts a Date instance or a number (ms since Unix epoch) as its first argument. If you start with a string representation of a date, you need to parse it into a Date object first (with theparse
orparseISO
functions for example).https://date-fns.org/v2.23.0/docs/format
Careful using strings in the Date constructor, it is discouraged by MDN because the implementation varies with each runtime.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date