简体   繁体   English

React:将 mongoDB 日期转换为人类可读的日期

[英]React: Converting mongoDB date to human readable date

A document stored in MongoDB has a "createdAt" property, which contains a timestamp.存储在 MongoDB 中的文档具有“createdAt”属性,其中包含时间戳。 Here we have an example of the timestamp:这里我们有一个时间戳的例子:

createdAt: 2021-10-26T12:24:33.433+00:00

Considering this date is today, how can I reproduce the following behavior?:考虑到这个日期是今天,我该如何重现以下行为?:

  • Display this date as "Today at 12:24 PM"将此日期显示为“今天下午 12:24”
  • Tomorrow, display this date as "Yesterday at 12:24 PM"明天,将此日期显示为“昨天下午 12:24”
  • From the day after tomorrow and beyond, display it as "26/10/2021 at 12:24 PM"从后天及以后,将其显示为“26/10/2021 at 12:24 PM”

I tried using the JavaScript's Date instance to compare both strings but I got into some trouble trying to convert the strings properly.我尝试使用 JavaScript 的 Date 实例来比较两个字符串,但在尝试正确转换字符串时遇到了一些麻烦。 I was wondering if there's any library that could ease the process or some conventional way to do it.我想知道是否有任何图书馆可以简化这个过程或一些传统的方法来做到这一点。

Since you mention using React, I assume that you have a Node running there somewhere.既然你提到使用 React,我假设你有一个 Node 在那里运行。 Maybe a create-react-app backend?也许是一个create-react-app后端? I will also assume ESM.我还将假设 ESM。

You would achieve something like this with date-fns;您可以使用 date-fns 实现类似的功能; see docs at https://date-fns.org/v2.25.0/docs/formatDistance请参阅https://date-fns.org/v2.25.0/docs/formatDistance 上的文档

$ npm i date-fns First, install dependency, then test it like below: $ npm i date-fns首先,安装依赖,然后如下测试:

import formatDistance from 'date-fns/formatDistance'

function TestComponent() {
   const dateStr = "2021-10-26T12:24:33.433+00:00";
   const str = formatDistance(
       new Date(dateStr),
       new Date()
   );
   return <h1>{str}</h1>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM