【问题标题】:How to find the time spend between two timestamps in React JS?如何在 React JS 中找到两个时间戳之间的时间?
【发布时间】:2021-02-24 07:00:44
【问题描述】:

我有一个应用程序,用户可以在其中发布内容,而所有其他用户都可以查看该帖子。所以我想在那个帖子中查看多久前当前帖子是发布的,例如“5 分钟前”或“2 天前”或“刚刚”等。

我有帖子的服务器时间戳 (Firebase)。让我们将此变量称为timestamp

【问题讨论】:

标签: javascript reactjs firebase


【解决方案1】:

你可以使用momentjs的fromNow创建一个实用函数:

import moment from 'moment'

export function getFromNow(
  date: moment.Moment | Date,
  suffix = 'ago'
) {
  let momentDate: moment.Moment
  if (moment.isMoment(date)) {
    momentDate = date
  } else {
    momentDate = moment(date)
  }
  return `${momentDate.fromNow(true)} ${suffix}`
}

【讨论】:

  • 如果你不使用 TypeScript,你可以删除打字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-12
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 2020-07-13
  • 2017-05-12
相关资源
最近更新 更多