[英]Relative Date in Moment.js using .fromNow() - how to get together years, months and days ago?
2015-02-01
- (1st Feb 2015) 假设我有一个日期字符串2015-02-01
- (2015年2月1日) 2016-07-02
(2nd Jul 2016) 今天我们有2016-07-02
(2016年7月2日) We can easily see that the older date took place approximately 1 year and 5 months and 1 day ago. 我们可以很容易地看到,旧的日期发生了约1年5个月和 1天前。
I wanted to achieve relative result like that using Moment.js, so I did: 我希望使用Moment.js获得相对结果,所以我做了:
return moment('2015-02-01).fromNow();
Unfortunately , library rounds the result and I get a year ago
, where almost half of the next year is ignored (missing 5 months and 1 day). 遗憾的是 , 图书馆的结果a year ago
我得到a year ago
,明年几乎有一半被忽略(缺少5个月和1天)。
The only available boolean argument passed to .fromNow()
is nothing that can help. 传递给.fromNow()
的唯一可用布尔参数是没有任何帮助的。 Is it possible to get full relative date where I could control breakdown even to hours, minutes and seconds if needed? 是否可以获得完整的相对日期,如果需要,我可以控制故障甚至是小时,分钟和秒?
You have a couple options depending on what direction you want to go with this. 根据您想要的方向,您可以选择几个选项。 Probably the most straightforward is to use a duration instead of .fromNow()
. 可能最直接的是使用持续时间而不是.fromNow()
。
Just do: 做就是了:
var diff = moment('2015-02-01').diff(moment(), 'milliseconds');
var duration = moment.duration(diff);
This gets you a duration type in moment, which you can get lots of information from. 这将为您提供持续时间类型,您可以从中获取大量信息。 For example: 例如:
duration.years(); //-1
duration.months(); //-4
duration.days();// -30
duration.hours(); //-8
Or if you want the units in aggregate: 或者如果你想要聚合的单位:
duration.asYears(); //-1.416481451250425
duration.asMonths(); //-16.997784898617585
And so on. 等等。 You can format this however you would like. 您可以根据需要格式化。
If you would like more advanced duration formatting you can check out this plugin . 如果您想要更高级的持续时间格式,可以查看此插件 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.