reactjs 如何使用mysql datetime中的date-fns返回相对时间?

x9ybnkn6  于 2023-02-04  发布在  React
关注(0)|答案(1)|浏览(133)

我想在我的react博客中添加一个相对时间... ago,而不使用moment.js,发布日期的格式是mysql datatime数据类型,比如2023-02-01 21:25:33
我在组件中尝试的是:
从“date-fns”导入{格式,格式相对,子天数}

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

}

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

但我得到错误:

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)

docs中我也找不到任何相关的例子,所以我想知道如何解决这个问题?

42fyovps

42fyovps1#

显然你不需要SubDays

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

}

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

相关问题