0

I'd like to add a relative time ... ago into my react blog posts without using moment.js. The post date is formatted in mysql datatime data type like 2023-02-01 21:25:33

What I tried in the component this:

import { format, formatRelative, subDays } from 'date-fns'

const formatDate = (date) => {
  return formatRelative(subDays(date), new Date())

}


<p>Posted  {formatDate(post.date) }</p>

But I get error:

Unhandled Thrown Error!
Invalid time value
RangeError: Invalid time value
    at format (http://localhost:3000/static/js/bundle.js:11517:11)
    at formatDate (http://localhost:3000/static/js/bundle.js:1341:170)
    at Single (http://localhost:3000/static/js/bundle.js:1396:36)
    at renderWithHooks (http://localhost:3000/static/js/bundle.js:47842:22)
    at mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:51128:17)
    at beginWork (http://localhost:3000/static/js/bundle.js:52424:20)
    at beginWork$1 (http://localhost:3000/static/js/bundle.js:57387:18)
    at performUnitOfWork (http://localhost:3000/static/js/bundle.js:56656:16)
    at workLoopSync (http://localhost:3000/static/js/bundle.js:56579:9)
    at renderRootSync (http://localhost:3000/static/js/bundle.js:56552:11)

I also could not find any relevant example in the docs. So I'm wondering how can I fix this?

blnks
  • 600
  • 5
  • 15
  • 1
    I never used date-fns but according to the docs, `subDays` requires two arguments (instead of only one as in your example): https://date-fns.org/v2.29.3/docs/subDays – dulange Feb 02 '23 at 19:52
  • Maybe you can take a look at this. Seems to be doing what you want. https://stackoverflow.com/questions/9129928/how-to-calculate-number-of-days-between-two-dates – Nikster Feb 02 '23 at 19:58

1 Answers1

1

Apparently you don't need subDays

const formatDate = (date) => {
  return formatRelative(date, new Date())

}


<p>Posted  {formatDate(post.date) }</p>
  • Wrong. Still gives the same error: `Invalid time value` – blnks Feb 02 '23 at 20:21
  • 1
    Look: https://codesandbox.io/s/date-fns-playground-forked-7opk65 – Adalcino Junior Feb 02 '23 at 20:41
  • For some reason I still get error on my react app. Here is the raw time value: `2023-01-31T16:50:18.000Z` when rendered on my react app. – blnks Feb 02 '23 at 22:15
  • I understand, strange that this happens. Do you have a github (or similar) repository that you can share your project with? It would make it easier to understand the problem. – Adalcino Junior Feb 03 '23 at 11:51