所以我撰寫了這個函式來測驗今天的日期是否在基于我的開始和結束日期的兩個陣列的給定范圍或時間段內。然后附加年份和測驗。如果它找不到一個句點,它回傳“NIR”或“不在范圍內”,否則它回傳一個帶有句點和年份的字串,我稍后在我的程式中使用它來執行其他幾個函式。
這個函式作業得很好,然后今天隨機開始回傳 NIR。我已經嘗試在每個步驟之間登錄,如果我設定 d = Date.parse("Oct 21, 2021") 而不是 Date.now() 它作業正常,我什至可以讓它作業。我很困惑有什么區別。
function findPeriod(offset = 0) {
const s = ["Aug 29", "Sept 12", "Sept 26", "Oct 10", "Oct 24", "Nov 7", "Nov 21", "Dec 5", "Dec 19", "Jan 2", "Jan 16", "Jan 30", "Feb 13", "Feb 27", "Mar 13", "Mar 27", "Apr 10", "Apr 24", "May 8", "May 22", "Jun 5", "Jun 19", "Jul 3", "Jul 17", "Jul 31", "Aug 14", "Aug 28", "Sept 11", "Sept 25"]; // Start of periods
const e = ["Sept 11", "Sept 25", "Oct 9", "Oct 23", "Nov 6", "Nov 20", "Dec 4", "Dec 18", "Jan 1", "Jan 15", "Jan 29", "Feb 12", "Feb 26", "Mar 12", "Mar 26", "Apr 9", "Apr 23", "May 7", "May 21", "Jun 4", "Jun 18", "Jul 2", "Jul 16", "Jul 30", "Aug 13", "Aug 27", "Sept 10", "Sept 24", "Oct 8"]; // End of periods
const y = '2021';
const p = ["Period 19", "Period 20", "Period 21", "Period 22", "Period 23", "Period 24", "Period 25", "Period 26", "Period 27", "Period 1"]; // Corresponding period
const d = Date.now();
let found = " ";
try {
for (let i = 0; i < p.length; i ) {
if (d >= Date.parse(s[i] ', ' y) && d <= Date.parse(e[i] ', ' y)) {
found = p[i offset] " " s[i offset] " to " e[i offset] `, ${y}`;
break;
} else {
found = "NIR";
}
}
return found;
} catch (err) {
console.log(err);
}
}
console.log(findPeriod());
uj5u.com熱心網友回復:
Date.now()為您提供包含小時、分鐘和秒的日期。這就是為什么今天(10 月 9 日 時間)大于您定義的時間段結束時間的原因。
又快又臟。首先通過轉換為日期字串來獲取沒有時間的日期:
const d = new Date(new Date().toDateString());
更新 正如 RobG 所提到的,您可以像這樣洗掉時間:
const d = new Date();
d.setHours(0,0,0,0);
function findPeriod(offset = 0) {
const s = ["Aug 29", "Sept 12", "Sept 26", "Oct 10", "Oct 24", "Nov 7", "Nov 21", "Dec 5", "Dec 19", "Jan 2", "Jan 16", "Jan 30", "Feb 13", "Feb 27", "Mar 13", "Mar 27", "Apr 10", "Apr 24", "May 8", "May 22", "Jun 5", "Jun 19", "Jul 3", "Jul 17", "Jul 31", "Aug 14", "Aug 28", "Sept 11", "Sept 25" ]; // Start of periods
const e = ["Sept 11","Sept 25", "Oct 9", "Oct 23", "Nov 6", "Nov 20", "Dec 4", "Dec 18", "Jan 1", "Jan 15", "Jan 29", "Feb 12", "Feb 26", "Mar 12", "Mar 26", "Apr 9", "Apr 23", "May 7", "May 21", "Jun 4", "Jun 18", "Jul 2", "Jul 16", "Jul 30", "Aug 13", "Aug 27", "Sept 10", "Sept 24", "Oct 8"]; // End of periods
const y = '2021';
const p = ["Period 19", "Period 20", "Period 21", "Period 22", "Period 23", "Period 24", "Period 25", "Period 26", "Period 27", "Period 1"]; // Corresponding period
const d = new Date(new Date().toDateString());
let found = " ";
try {
for (let i = 0; i < p.length; i ) {
if (d >= Date.parse(s[i] ', ' y) && d <= Date.parse(e[i] ', ' y)) {
found = p[i offset] " " s[i offset] " to " e[i offset] `, ${y}`;
break;
} else {
found = "NIR";
}
}
return found;
} catch (err) {
console.log(err);
}
}
console.log(findPeriod());
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/321382.html
標籤:javascript 日期 约会时间
上一篇:從微時間陣列中獲取最新資訊
