我有兩個函式,一個查找本周的檔案,另一個查找本月的檔案。我想從本月的檔案中提取/過濾本周的檔案。
filterThisWeek(files) {
const firstDayOfWeek = new Date(new Date().setDate(new Date().getDate() - new Date().getDay()));
return this.filterToday(files).filter((f) => {
return f.date >= firstDayOfWeek;
});
},
filterThisMonth(files) {
const today = new Date();
return files.filter((f) => {
return (
new Date(f.date).getMonth() === today.getMonth() &&
new Date(f.date).getFullYear() === today.getFullYear()
);
});
使用 filterThisWeek 函式我想從本月提取本周的檔案。所以 filterThisMonth 函式應該找到這個月的檔案,除了本周的檔案。我想以最有效的方式做到這一點,但我不知道該怎么做。
uj5u.com熱心網友回復:
我建議創建函式getStartOfWeek()并getStartOfMonth()建立所需的日期閾值。
然后,我們將使用這些在過濾器函式中創建所需的限制,filterThisWeek()并且filterThisMonth().
filterThisWeek() 應回傳日期大于或等于一周開始的任何檔案,而 filterThisMonth() 應回傳日期大于或等于月初且小于一周開始的任何檔案;
function getStartOfWeek(date) {
const dt = new Date(date.getFullYear(), date.getMonth(), date.getDate());
const offset = dt.getDate() - (dt.getDay() === 0 ? 6: dt.getDay() - 1);
return new Date(dt.setDate(offset));
}
function getStartOfMonth(date) {
return new Date(date.getFullYear(), date.getMonth(), 1)
}
function filterThisWeek(files, referenceDate = new Date()) {
const lowerThreshold = getStartOfWeek(referenceDate);
return files.filter(file => file.date >= lowerThreshold);
}
function filterThisMonth(files, referenceDate = new Date()) {
const lowerThreshold = getStartOfMonth(referenceDate);
const upperThreshold = getStartOfWeek(referenceDate);
return files.filter(file => file.date >= lowerThreshold && file.date < upperThreshold);
}
function formatFile(file) {
return `${file.date.toLocaleDateString('sv')}`;
}
const testFiles = Array.from( { length: 14 }, (v, k) => {
return { date: new Date(Date.now() - k*86400*1000)};
})
console.log('This weeks files:', filterThisWeek(testFiles).map(formatFile));
console.log('This months files:', filterThisMonth(testFiles).map(formatFile));
.as-console-wrapper { max-height: 100% !important; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/510330.html
