如何使用Moment.js? [英] How to use Moment.js?
问题描述
我无法关注 Moment.js文档,并需要一些设置帮助。我在我的网页上正确引用了 moment.min.js
文件,如下所示:
I'm unable to follow the Moment.js documentation, and need some help with setting it up. I've referenced the moment.min.js
file properly on my webpage like so:
<script src="/js/moment.min.js"></script>
来到我的网页的HTML部分,我在同一页面上有两个不同的日期时间:
Coming to the HTML part of my webpage, I have two different datetime's on the same page:
发布日期
<time class="pubdate" datetime="2012-06-09T12:32:10-04:00" pubdate>
June 09, 2012
</time>
上次修改日期
<time class="updated" itemprop="dateModified" datetime="2012-06-09T12:32:10-04:00">
June 9, 2012 ~ 12:32
</time>
重要!相对日期解析不应超出昨天 。至于其他所有内容,< time>
标签应显示没有JavaScript的确切日期时间 - 即Moment.js不应触及或解析过去的日期昨天。
Important! The relative date parsing shouldn't go beyond "yesterday". As for everything beyond, the <time>
tags should display the exact datetime's they would without the JavaScript -- i.e. Moment.js shouldn't touch or parse dates that are past "yesterday".
现在,为了使库完成前面提到的工作,我需要在库引用之后调用一个函数。所以,问题是,该功能应该是什么? (使用jQuery很好,因为我已经在我的网页上引用了这个库。)
Now, to make the library do its job as aforementioned, I need to call a function after the library reference. So, the question is, what should the function be? (Using jQuery is fine, as I already reference the library on my webpage.)
推荐答案
请指出你的问题。我假设你想要一个相对日期解析,最大值应该是昨天。
Please specify your question. I'm assuming you want a relative date parsing and the maximum should be "yesterday".
我从未使用过moment.js,但据文档说,它很漂亮简单。
I never used moment.js but as far as the docs say, it's pretty simple.
使用 var now = moment();
作为当前日期。然后使用 var time = moment($(e).attr('datetime'))解析DOM中的每个
time
-Tag;
Use var now = moment();
as your current date. Then parse every time
-Tag in your DOM with var time = moment($(e).attr('datetime'));
要检查差异,请使用 diff()
方法:
To check the difference use the diff()
method:
if(now.diff(time, 'days') <= 1) {
// getting the relative output
}
使用 var ago = now.from(time)
获取相对输出并用前
变量替换DOM中的时间。
Use var ago = now.from(time)
to get the relative output and replace the time in your DOM with your ago
variable.
根据评论更新:
好的,未经测试,但这是基本想法:
Okay, well untested, but that's the basic idea:
更新了代码。
var now = moment();
$('time').each(function(i, e) {
var time = moment($(e).attr('datetime'));
if(now.diff(time, 'days') <= 1) {
$(e).html('<span>' + time.from(now) + '</span>');
}
});
这篇关于如何使用Moment.js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!