Javascript 如何使用 Moment.js?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10967736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:49:40  来源:igfitidea点击:

How to use Moment.js?

javascriptjqueryrelative-datemomentjs

提问by its_me

I'm unable to follow the Moment.js documentation, and need some help with setting it up. I've referenced the moment.min.jsfile properly on my webpage like so:

我无法遵循Moment.js 文档,需要一些帮助来设置它。我已经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 -- i.e. Moment.js shouldn't touch or parse dates that are past "yesterday".

重要的!相对日期解析不应超出“昨天”。至于以后的所有内容,<time>标签应该显示他们在没有 JavaScript 的情况下会显示的确切日期时间——即 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 很好,因为我已经在我的网页上引用了这个库。)

回答by Johannes Klau?

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();as your current date. Then parse every time-Tag in your DOM with var time = moment($(e).attr('datetime'));

使用var now = moment();作为当前日期。然后解析timeDOM 中的每个-Tagvar 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 agovariable.

使用var ago = now.from(time)以获得相对输出和更换时间与你的DOMago变量。

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

回答by kodkod

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 lastWeekand nextWeekto full date-time format (e.g. 'L').

如果您没有在昨天之前格式化日期兴趣,只是改变的格式lastWeek,并nextWeek以完整的日期-时间格式(例如'L')。



UPDATE 2013-09-06Apparently it has a new syntax that also enables you to localize it:

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

回答by its_me

Thanks to @JohannesKlau? for the code. This is basically how I executed his answer and how I am referencing the code on my website.

感谢@JohannesKlau?对于代码。这基本上就是我如何执行他的回答以及我如何引用我网站上的代码。

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

Where, moment.min.jsis the Moment.js library, and moment.executor.jshas 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.jsand add the aforementioned code right in it, at the end. This way, you will be saving one additional HTTP request. :P

PS:您实际上可以编辑moment.min.js并在最后添加上述代码。这样,您将保存一个额外的 HTTP 请求。:P

回答by Scott Davey

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')
  • switches to a different format when +-1 day from now (e.g. Last Tuesday at 11:45 PM)
  • 用给定的类更新所有元素
  • 让它们每分钟更新一次(所以“1 分钟前”变成“2 分钟前”)
  • 从现在起 +-1 天时切换到不同的格式(例如上周二晚上 11:45)

Here's a JSFiddlefor 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);

})();