简体   繁体   English

如何在反应中将时间戳转换为时间前格式?

[英]How to convert timestamps to time ago format in react?

假设我有这种格式的创建时间:(2021-06-30 15:36:50.375+03),我想将其转换为时间前格式,例如 5 分钟前或 2 小时前,那么我该怎么做在javascript(反应)中?

Doing it by yourself will require a lot of codes, continuous fixing and improvement.自己做需要大量的代码,不断的修复和改进。 You can either use a code snippet of another coder, or better you can use some JS (React/Node/etc.) npm packages, like moment https://www.npmjs.com/package/moment .您可以使用另一个编码器的代码片段,或者更好的是您可以使用一些 JS(React/Node/等)npm 包,例如moment https://www.npmjs.com/package/moment The advantage of moment is that it's maintained, high quality and very popular, 16M downloads a week, 45.8K stars in Github. moment 的优势在于它的维护,高质量和非常受欢迎,每周下载 1600 万次,在 Github 上有 45.8K 星。

As an example, moment uses the method fromNow() :例如, moment 使用方法fromNow()

import moment from 'moment';

// other codes

const timeago = moment(data.created_at).fromNow();

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

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