gpt4 book ai didi

javascript - moment.js - 测试日期是今天、昨天、一周或两周前

转载 作者:IT王子 更新时间:2023-10-29 03:09:06 29 4
gpt4 key购买 nike

我正在尝试使用 moment.js 来了解日期是今天、昨天、1 周前还是更早(2 周前或更早)。

前两种情况我已经这样做了:

var today = moment().startOf('day');
var yesterday = moment().subtract(1, 'days').startOf('day');

if (moment(localTime).isSame(today, 'd')) // today
// do something
if (moment(localTime).isSame(yesterday, 'd')) // yesterday
// do something

对吗?

但是,我如何检查日期是一周前还是更早(例如两周前)?

最佳答案

这里有一些有用的东西:

var REFERENCE = moment("2015-06-05"); // fixed just for testing, use moment();
var TODAY = REFERENCE.clone().startOf('day');
var YESTERDAY = REFERENCE.clone().subtract(1, 'days').startOf('day');
var A_WEEK_OLD = REFERENCE.clone().subtract(7, 'days').startOf('day');

function isToday(momentDate) {
return momentDate.isSame(TODAY, 'd');
}
function isYesterday(momentDate) {
return momentDate.isSame(YESTERDAY, 'd');
}
function isWithinAWeek(momentDate) {
return momentDate.isAfter(A_WEEK_OLD);
}
function isTwoWeeksOrMore(momentDate) {
return !isWithinAWeek(momentDate);
}

console.log("is it today? ..................Should be true: "+isToday(moment("2015-06-05")));
console.log("is it yesterday? ..............Should be true: "+isYesterday(moment("2015-06-04")));
console.log("is it within a week? ..........Should be true: "+isWithinAWeek(moment("2015-06-03")));
console.log("is it within a week? ..........Should be false: "+isWithinAWeek(moment("2015-05-29")));
console.log("is it two weeks older or more? Should be false: "+isTwoWeeksOrMore(moment("2015-05-30")));
console.log("is it two weeks older or more? Should be true: "+isTwoWeeksOrMore(moment("2015-05-29")));

Check a JSFiddle demo进行更多测试,因此您可以根据需要针对具体情况进行调整。

关于javascript - moment.js - 测试日期是今天、昨天、一周或两周前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30668373/

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