在moment.js中,如果只显示当前年份,则不想显示年份。

5
我有这段代码,可以将日期转换为易读的时间格式。
$('time').each(function (i, e) {

        if ($(e).attr("class") == 'mtime') {

            var now = moment();
            moment.lang('en', {
                calendar : {
                    lastDay : '[Yesterday] LT',
                    sameDay : 'LT',
                    nextDay : '[Tomorrow,] LT',
                    lastWeek : 'ddd LT',
                    nextWeek : 'ddd LT',
                    sameElse : 'MMM D[/]YY' //something to do with this?
                }

            });

            var elem = $(e).attr('datetime');
            var time = moment($(e).attr('datetime'));
            var diff = now.diff(time, 'days');

            $(e).html(time.calendar());

        }

});

返回的输出:

<time class="mtime" datetime="2016-02-26 10:31:22" title="2016-02-26 10:31:22">Feb 26/16</time>

问题是如果是当前年份,如何隐藏年份。如果是过去的年份,则按“M/D/YY”格式进行格式化。
- <time>Feb 26</time> <!--// current year -->
- <time>12/25/15</time> <!--// last year -->
- <time>8/1/14</time> <!--// last year -->

请大家提供建议!谢谢你们! TIA
3个回答

5
自版本2.14.0起,我们可以将回调函数传递给特定的时刻上下文:
sameElse: function() {
  if (this.years() === now.years()) {
    return 'MMM D'
  } else {
    return 'M/D/YY';
  }
}

$('time').each(function(i, e) {
  if ($(e).attr("class") == 'mtime') {
    var now = moment();
    moment.lang('en', {
      calendar: {
        lastDay: '[Yesterday] LT',
        sameDay: 'LT',
        nextDay: '[Tomorrow,] LT',
        lastWeek: 'ddd LT',
        nextWeek: 'ddd LT',
        sameElse: function() {
          if (this.years() === now.years()) {
            return 'MMM D'
          } else {
            return 'M/D/YY';
          }
        }
      }
    });
    var elem = $(e).attr('datetime');
    var time = moment($(e).attr('datetime'));
    var diff = now.diff(time, 'days');
    $(e).html(time.calendar());
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<time class="mtime" datetime="2016-02-26 10:31:22"></time> <br />
<time class="mtime" datetime="2015-12-25 10:31:22"></time> <br />
<time class="mtime" datetime="2014-08-01 10:31:22"></time> <br />


不知道那是可能的!哈哈!谢谢!向@Maciej致敬! - mrrsb
注意:不要使用箭头函数 ()=>{},因为它与常规的 function(){} 有不同的 this - Serhii Harbovskyi
有没有一种方法可以在 format() 上实现,而不是在 calendar() 上实现? - NanoNova

0
你可以定义自己的自定义日历格式,比如说:'thisYear'。

moment.calendarFormat = function (myMoment, now) {
    var diff = myMoment.diff(now, 'days', true);
    var nextMonth = now.clone().add(1, 'month');

    var retVal = (myMoment.year() === now.year()) ? 'thisYear' :
        diff < -6 ? 'sameElse' :
        diff < -1 ? 'lastWeek' :
        diff < 0 ? 'lastDay' :
        diff < 1 ? 'sameDay' :
        diff < 2 ? 'nextDay' :
        diff < 7 ? 'nextWeek' : 'sameElse';
        
    console.log(retVal);
    return retVal;
};

$('time').each(function (i, e) {

        if ($(e).attr("class") == 'mtime') {
            var formats = {
                    lastDay : '[Yesterday] LT',
                    sameDay : 'LT',
                    nextDay : '[Tomorrow,] LT',
                    lastWeek : 'ddd LT',
                    nextWeek : 'ddd LT',
                    thisYear : 'MMM D',
                    sameElse : 'M/D/YY'
            };

            var elem = $(e).attr('datetime');
            var time = moment(elem);

            $(e).html(time.calendar(moment(), formats));
        }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<time class="mtime" datetime="2016-02-26 10:31:22"></time> <br />
<time class="mtime" datetime="2015-12-25 10:31:22"></time> <br />
<time class="mtime" datetime="2014-08-01 10:31:22"></time> <br />


0

看起来你的代码已经有了大部分需要的内容。你只需要将你的“now”变量与从时间DOM属性返回的值进行比较。

P.S. 经过进一步查看代码,我做出了比最初想象中更多的更改。

 // instead is checking for the time elements with the mtime class, just select them using the jQuery class selector. It's far more efficient.
    $('.mtime').each(function(i, e) {

        var elem = $(e).attr('datetime'); // grabs the time DOM element and caches it.
        var eDateTime = elem.attr('datetime'); // could also just check against this. No real need to wrap momentJS around it.
        var now = moment(); // gets the current now datetime.
        var time = moment(eDateTime); // this grabs the datetime from the element and wraps moment around it. 

        moment.lang('en', {
          calendar: {
            lastDay: '[Yesterday] LT',
            sameDay: 'LT',
            nextDay: '[Tomorrow,] LT',
            lastWeek: 'ddd LT',
            nextWeek: 'ddd LT',
            sameElse: function() {
              if (time === now) { // compare the datetimes
                return 'MMM D'
              } else {
                return 'M/D/YY';
              }
            }
          }

            if (time !== now) { // compare the datetimes. If they do not match it renders.
                elem.html(time.calendar()); 
            }
        }
  });

希望这有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接