简体   繁体   English

React将JSON日期转换为相对时间

[英]React convert JSON date to relative time

How do I convert this: 我该如何转换:

2017-08-14T23:28:56.782Z

Into relative time eg "21d". 转换为相对时间,例如“ 21d”。 If there is an npm dependency I can use that too. 如果有npm依赖项,我也可以使用。

there are some useful library like momentjs which will easy the way. 有一些有用的库,例如momentjs ,可以简化方法。

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

Using moment.js, you can do moment("2017-08-14T23:28:56.782Z").fromNow(); 使用moment.js,您可以执行moment("2017-08-14T23:28:56.782Z").fromNow(); . This will give you 21 days ago 这将在21天前给您

 console.log(moment("2017-08-14T23:28:56.782Z").fromNow()); 
 <script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js'></script> 

If you mean 21 days ago, then Moment.js is convenient for things like that. 如果您的意思是21天前,那么Moment.js对于此类事情很方便。 There is also react-datetime , but I don't have any experience using it with React, so I can't comment on its efficacy or ease of use. 也有react-datetime ,但是我没有在React上使用它的任何经验,所以我不能评论它的功效或易用性。

使用moment.js。
npm install moment

moment([2017, 9, 4]).fromNow(); 

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

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