简体   繁体   English

如何在 React JS 中找到两个时间戳之间的时间?

[英]How to find the time spend between two timestamps in React JS?

I have an application where the user can post something and all other users can view that post.我有一个应用程序,用户可以在其中发布某些内容,而所有其他用户都可以查看该帖子。 So I want to view in that post that how much time ago the current post was posted, like "5 mins ago" or "2 days ago" or "Just Now", etc.所以我想在那个帖子中查看当前帖子发布的时间,例如“5 分钟前”或“2 天前”或“刚刚”等。

I have the server timestamp (Firebase) of the post.我有帖子的服务器时间戳(Firebase)。 Let's call this variable as timestamp .让我们将此变量称为timestamp

You can create a utility function using momentjs's fromNow :您可以使用 momentjs 的fromNow 创建实用程序 function

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}`
}

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

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