【问题标题】:How to convert UNIX timestamp into relative date like whatsapp last seen status with moment.JS如何将 UNIX 时间戳转换为相对日期,例如使用 moment.JS 的 whatsapp 上次看到状态
【发布时间】:2020-12-02 06:04:12
【问题描述】:

我想在上次看到的状态中显示一个 UNIX 时间戳,这与 WhatsApp 在 javascript 中所做的相同。我正在使用moment.js,据我所知,我们可以格式化日期,也可以使用.fromNow(),它给出了一个相对日期,但不是我想要的。

例如, 让 Unix 时间戳:1606908420

如果我使用moment.unix(1606908420).formNow(),结果将是few seconds ago 或类似的东西

但我正在寻找的是,它应该显示Today 11:30 am

同样

For a date of yesterday, it should show: Yesterday 11:30 am
For a date of day before yesterday, it should show: Mon 11:30 am

Any date of last week or earlier, it should show 25-11-2020 

谁能帮我实现这个目标?

【问题讨论】:

  • 您根本不想要一个相对日期。检查日期的年龄并根据使用的格式决定
  • 好的,所以基本上我需要过滤日期,如果今天是昨天,或者根据我设置的标语行更早的任何日期?
  • 尝试像这样使用时刻日历:moment.unix(UNIX_TIMESTAMP).calendar()
  • @TabrezBasha,是的,它的工作方式就像我想要的那样 :)

标签: javascript reactjs react-native momentjs


【解决方案1】:

将 UNIX 时间戳转换为日期

  1. 使用toDate()方法

    {new Date(timestamp?.toDate()).toUTCString()}

    Wed, 2 Dec 2020 12:00:00 GMT

  2. 使用时刻方法

    {moment.unix(order.data.created).format("MMMM Do YYYY, h:mma")}

我强烈推荐第二个时刻给你。了解更多 moment docs

【讨论】:

    猜你喜欢
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    相关资源
    最近更新 更多