gpt4 book ai didi

javascript - 不想只在 moment.js 中显示当前年份的年份

转载 作者:行者123 更新时间:2023-11-29 10:08:03 24 4
gpt4 key购买 nike

我有这段代码可以将日期转换为可读的时间格式

$('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 -->

请大家多多指教!时间差

最佳答案

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 />

关于javascript - 不想只在 moment.js 中显示当前年份的年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39360916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com