简体   繁体   English

如何使用Moment.js?

[英]How to use Moment.js?

I'm unable to follow the Moment.js documentation , and need some help with setting it up. 我无法关注Moment.js文档 ,需要一些设置帮助。 I've referenced the moment.min.js file properly on my webpage like so: 我在我的网页上正确引用了moment.min.js文件,如下所示:

<script src="/js/moment.min.js"></script>

Coming to the HTML part of my webpage, I have two different datetime's on the same page: 来到我的网页的HTML部分,我在同一页面上有两个不同的日期时间:

Published Date 发布日期

<time class="pubdate" datetime="2012-06-09T12:32:10-04:00" pubdate>
    June 09, 2012
</time>

Last Modified Date 上次修改日期

<time class="updated" itemprop="dateModified" datetime="2012-06-09T12:32:10-04:00">
    June 9, 2012 ~ 12:32
</time>

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 -- ie Moment.js shouldn't touch or parse dates that are past "yesterday". 至于其他所有内容, <time>标签应显示没有JavaScript的确切日期<time> - 即Moment.js不应触及或解析过去“昨天”的日期。

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.) (使用jQuery很好,因为我已经在我的网页上引用了库。)

Please specify your question. 请指出你的问题。 I'm assuming you want a relative date parsing and the maximum should be "yesterday". 我假设你想要一个相对日期解析,最大值应该是“昨天”。

I never used moment.js but as far as the docs say, it's pretty simple. 我从未使用过moment.js,但就文档而言,它非常简单。

Use var now = moment(); 使用var now = moment(); as your current date. 作为你当前的日期。 Then parse every time -Tag in your DOM with var time = moment($(e).attr('datetime')); 然后分析每time -Tag在DOM与var time = moment($(e).attr('datetime'));

To check the difference use the diff() method: 要检查差异,请使用diff()方法:

if(now.diff(time, 'days') <= 1) {
    // getting the relative output
}

Use var ago = now.from(time) to get the relative output and replace the time in your DOM with your ago variable. 使用var ago = now.from(time)获取相对输出,并用您ago变量替换DOM中的时间。

Update based on comment : 根据评论更新

Okay, well untested, but that's the basic idea: 好的,未经测试,但这是基本的想法:

Updated the code. 更新了代码。

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>');
    }
});

You can also use the moment().calendar() function, which will format for you dates close to today (up to a week from today): 您还可以使用moment().calendar()函数,该函数将为您设置接近今天的日期格式(从今天起最多一周):

$('time').each(function(i, e) {
  var time = moment($(e).attr('datetime'));

  $(e).html('<span>' + time.calendar() + '</span>');
});​

You can customize the format strings with this code: 您可以使用以下代码自定义格式字符串:

moment.calendar = {
  lastDay : '[Yesterday at] LT',
  sameDay : '[Today at] LT',
  nextDay : '[Tomorrow at] LT',
  lastWeek : '[last] dddd [at] LT',
  nextWeek : 'dddd [at] LT',
  sameElse : 'L'
};

If you are not interested in formatting dates prior to yesterday, just change the formats of lastWeek and nextWeek to full date-time format (eg 'L' ). 如果您对昨天之前的日期格式不感兴趣,只需将lastWeeknextWeek的格式更改为完整日期时间格式(例如'L' )。


UPDATE 2013-09-06 Apparently it has a new syntax that also enables you to localize it: 更新2013-09-06显然它有一个新的语法,也可以让你本地化它:

moment.lang('en', {
  calendar: {
    lastDay : '[Yesterday at] LT',
    sameDay : '[Today at] LT',
    nextDay : '[Tomorrow at] LT',
    lastWeek : '[last] dddd [at] LT',
    nextWeek : 'dddd [at] LT',
    sameElse : 'L'
  }
});

Thanks to @JohannesKlauß for the code. 感谢@JohannesKlauß的代码。 This is basically how I executed his answer and how I am referencing the code on my website. 这基本上就是我如何执行他的答案以及我如何引用我网站上的代码。

<script src="/js/moment.min.js"></script>
<script src="/js/moment.executor.js"></script>

Where, moment.min.js is the Moment.js library, and moment.executor.js has this code (courtesy of Johannes): 其中, moment.min.js是Moment.js库,而moment.executor.js有这段代码(由Johannes提供):

jQuery(document).ready(function($){

    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>');
        }
    });

});

PS: You can actually edit moment.min.js and add the aforementioned code right in it, at the end. PS:您可以实际编辑moment.min.js并在其末尾添加上述代码。 This way, you will be saving one additional HTTP request. 这样,您将保存一个额外的HTTP请求。 :P :P

Extending @its_me's implementation above, here's a version that 扩展@ its_me的实现,这是一个版本

  • updates all elements with a given class 使用给定的类更新所有元素
  • keeps them updated every minute (so '1 minute ago' becomes '2 minutes ago') 让它们每分钟都更新(所以'1分钟前'成为'2分钟前''
  • switches to a different format when +-1 day from now (eg Last Tuesday at 11:45 PM) 从现在起+ 1天后切换到不同的格式(例如,上周二晚上11:45)

Here's a JSFiddle for you to play with. 这是一个可以玩的JSFiddle

Your HTML: 你的HTML:

<time class="cw-relative-date" datetime="2014-06-09T12:32:10-00:00"></time>

The JS to include: JS包括:

(function () {

// Define a function that updates all relative dates defined by <time class='cw-relative-date'>
var updateAllRelativeDates = function() {
        $('time').each(function (i, e) {
            if ($(e).attr("class") == 'cw-relative-date') {

                // Initialise momentjs
                var now = moment();
                moment.lang('en', {
                    calendar : {
                        lastDay : '[Yesterday at] LT',
                        sameDay : '[Today at] LT',
                        nextDay : '[Tomorrow at] LT',
                        lastWeek : '[Last] dddd [at] LT',
                        nextWeek : 'dddd [at] LT',
                        sameElse : 'D MMM YYYY [at] LT'
                    }
                });

                // Grab the datetime for the element and compare to now                    
                var time = moment($(e).attr('datetime'));
                var diff = now.diff(time, 'days');

                // If less than one day ago/away use relative, else use calendar display
                if (diff <= 1 && diff >= -1) {
                    $(e).html('<span>' + time.from(now) + '</span>');
                } else {
                    $(e).html('<span>' + time.calendar() + '</span>');
                }
            }
        });
    };

// Update all dates initially
updateAllRelativeDates();

// Register the timer to call it again every minute
setInterval(updateAllRelativeDates, 60000);

})();

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

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