Replies: 1 comment
-
Your example string input works fine with either import { parseISO, parseJSON, formatDistanceToNow } from "date-fns";
const input = "2021-01-06T18:35:16.000Z";
// const parsedDate = parseJSON(input);
// const parsedDate = parseISO(input);
const parsedDate = new Date(input);
const res = formatDistanceToNow(parsedDate);
console.log(res); // over 1 year |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello,
I have been trying to take a string from my database of the format "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", which appears to be ISO8601 format, and I've found that I can parse it using the parseJSON function as a wrapper to get the date string into a Date object from the string. However, I can't use the parseISO function or I experience an invalid format error.
My ultimate goal is to get the string into a Date format and then processed by the formatDistanceToNow function. And I'm able to output formatDistanceToNow(new Date()), which I ran as a sanity check, but I can't get formatDistanceToNow(new Date(parseJSON(date))) or formatDistanceToNow(parseJSON(date)) to work without another invalid format error.
I have also tried formatDistanceToNow(new Date(year, month, date, hours, minutes, seconds)), which works when I feed raw numbers as parameters, but my application gives me an invalid format error when I attempt to pass variables as parameters to the formatDistanceToNow function.
Is there a recommended way to take a string of the format above, and manipulate it to easily show the time elapsed? I've imported the ESM node module within a NextJS application, but am struggling with manipulating the date.
Also, I looked for a similar post, but was unsuccessful in finding a similar post, but thanks in advance!
Beta Was this translation helpful? Give feedback.
All reactions