在Javascript或Typescript中,可以使用以下步骤从常规日期列表中过滤出当前周的日期:
Date
对象获取当前日期,可以通过new Date()
来创建一个表示当前时间的对象。Date
对象的方法,如getDay()
获取当前日期是星期几,getDate()
获取当前日期是几号,以及setDate()
设置日期,可以计算出当前周的起始日期和结束日期。Date
对象的方法,如getTime()
获取日期的时间戳,可以将日期转换为毫秒数进行比较。将符合当前周起始日期和结束日期之间的日期添加到一个新的数组中。以下是一个示例代码,演示如何在Javascript中从常规日期列表中过滤出当前周的日期:
function filterCurrentWeekDates(dateList) {
const currentDate = new Date();
const currentDay = currentDate.getDay();
const currentMonth = currentDate.getMonth();
const currentYear = currentDate.getFullYear();
const startDate = new Date(currentYear, currentMonth, currentDate.getDate() - currentDay);
const endDate = new Date(currentYear, currentMonth, currentDate.getDate() + (6 - currentDay));
const filteredDates = dateList.filter(date => {
const d = new Date(date);
return d >= startDate && d <= endDate;
});
return filteredDates;
}
// 示例用法
const dateList = ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05', '2022-01-06', '2022-01-07'];
const filteredDates = filterCurrentWeekDates(dateList);
console.log(filteredDates);
在上述示例代码中,filterCurrentWeekDates
函数接受一个常规日期列表作为参数,返回一个过滤后的当前周日期列表。函数首先获取当前日期的星期几,然后计算出当前周的起始日期和结束日期。接下来,使用filter
方法遍历日期列表,将符合当前周起始日期和结束日期之间的日期添加到新的数组中,并返回该数组。
对于这个问题,腾讯云没有特定的产品与之相关。
领取专属 10元无门槛券
手把手带您无忧上云