gpt4 book ai didi

javascript - 使用 MomentJS 确定日期是今天还是过去?

转载 作者:太空宇宙 更新时间:2023-11-04 15:48:39 25 4
gpt4 key购买 nike

我正在构建一个仅显示当前月份的迷你日历,我已经弄清楚如何绘制日历,这是代码:

代码:

var month  = moment(),
index = 0,
maxDay = month.daysInMonth(),
start = month.startOf("month"),
offset = (start.isoWeekday() - 1 + 7) % 7; // start from monday

var week = []; // holds the weeks
var days = []; // holds the days

do {

var dayIndex = index - offset;

if(dayIndex >= 0 && dayIndex < maxDay){
days.push({
number: dayIndex + 1,
isPast: null, // stuck here boolean
isToday: null // stuck here boolean
})
}

if(index % 7 === 6){
week.push(days);
console.log(week);
days = [];

if (dayIndex + 1 >= maxDay) {
break;
}
}

index += 1;
} while(true);

这很好用,我遇到的唯一问题是弄清楚这一天是今天还是过去?

代码也在这里:https://jsfiddle.net/chghb3Lq/3/

最佳答案

时刻有isBefore , isAfterisSame比较时刻的函数,正如文档所说:

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

<小时/>

您可以使用 momentjs 以简单的方式实现代码中的一些内容,而无需自己重新实现:

使用这些建议,您的代码可能如下所示:

var day = moment().startOf('month');
var endOfMonth = moment().endOf('month');

var week = [];
var month = [];

while( day.isBefore(endOfMonth) ){
week.push({
number: day.date(),
isPast: moment().isAfter(day, 'day'),
isToday: moment().isSame(day, 'day')
});
if( day.day() === 0 ){
month.push(week);
week = [];
}
day.add(1, 'day');
}

console.log(month);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

关于javascript - 使用 MomentJS 确定日期是今天还是过去?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43330444/

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