I'm working with a JSON file where the 'createdAt' field contains strings like '1 week ago' and '2 days ago'. I want to update these dynamically based on the current date, so '1 week ago' would change to '2 weeks ago' a week from now, and so on. I'm hoping there's a more efficient approach than hardcoding specific values or using a switch statement for each possible string. Any suggestions?
5 Answers
Have you thought about transforming those date strings into ISO format just once? Working with the raw strings isn't ideal, and converting them to actual dates would simplify things a lot.
Absolutely! Fixing the format now will save you a ton of headaches later.
When pulling in data like this, it's a challenge. If you can control the input format, aim for `Date.prototype.toISOString`. If you can’t, but the strings stick to a specific format like `${number} ${period} ago`, you could split the string and calculate the date based on that. Just be ready for variations!
It's usually best to start from actual date strings in ISO format. When you need to display data, you can convert it just before rendering. This way, your data stays clean and your conversion logic is separated.
That’s true! Handling variable formats can get tricky. If the patterns change often, you might need to adjust your approach for each case.
I see your point; without knowing the reference time, you’re in a tough spot. Strings like '1 week ago' can be quite ambiguous if you’re unsure when they were last updated. Using date-fns' formatRelative function is a good call, but you'll need actual date references for that approach to work.

That makes sense! I was actually considering some regex and a switch case to get it done on a sample, but rewriting it to ISO sounds like the cleaner option.