此代碼減去日期:
const moment = require("moment");
const currentDate = new Date();
// #NOTE:
// By midnight, I mean at the end of the current day
const day_to_add = 1 * 24 * 60 * 60 * 1000;
const current_day_at_midnight_date = new Date(
currentDate.setHours(0, 0, 0, 0) day_to_add
);
const twenty_eight_days_to_remove = 27 * 24 * 60 * 60 * 1000;
const twenty_eight_days_ago_date = new Date(
currentDate - twenty_eight_days_to_remove
);
const formatted_first_day = moment(current_day_at_midnight_date).format(
"YYYY-MM-D"
);
const formatted_last_day = moment(twenty_eight_days_ago_date).format(
"YYYY-MM-D"
);
console.log(
"?? ~ file: add_remove_date.js ~ line 17 ~ formatted_first_day",
formatted_first_day
);
console.log(
"?? ~ file: add_remove_date.js ~ line 21 ~ formatted_last_day",
formatted_last_day
);
這是結果:
?? ~ 檔案:add_remove_date.js ~ 第 17 行 ~ formatted_first_day 2021-12-23
?? ~ 檔案:add_remove_date.js ~ 第 21 行 ~ formatted_last_day 2021-11-25
如您所見,它按預期減去了 28 天。
此代碼添加日期:
const moment = require("moment");
const currentDate = new Date();
// #NOTE:
// By midnight, I mean at the end of the current day
const day_to_add = 1 * 24 * 60 * 60 * 1000;
const current_day_at_midnight_date = new Date(
currentDate.setHours(0, 0, 0, 0) day_to_add
);
const twenty_eight_days_to_add = 27 * 24 * 60 * 60 * 1000;
const twenty_eight_days_later_date = new Date(
currentDate twenty_eight_days_to_add
);
const formatted_first_day = moment(current_day_at_midnight_date).format(
"YYYY-MM-D"
);
const formatted_last_day = moment(twenty_eight_days_later_date).format(
"YYYY-MM-D"
);
console.log(
"?? ~ file: add_remove_date.js ~ line 17 ~ formatted_first_day",
formatted_first_day
);
console.log(
"?? ~ file: add_remove_date.js ~ line 21 ~ formatted_last_day",
formatted_last_day
);
這基本上是相同的代碼。我只是用 替換了 -。
但是,它不起作用。這是結果:
?? ~ 檔案:add_remove_date.js ~ 第 17 行 ~ formatted_first_day 2021-12-23
?? ~ 檔案:add_remove_date.js ~ 第 21 行 ~ formatted_last_day 2021-12-22
出于某種奇怪的原因,添加的結果formatted_last_day總是在前一天formatted_first_day。
知道這里發生了什么嗎?
uj5u.com熱心網友回復:
日期是物件。如果對它們使用運算子,它們將被強制轉換為運算子支持的其他型別。在 JavaScript 中,字串是這里的首選,然后是數字,所以......
=> 強制為字串-=> 強制為數字(-字串不支持)
所以,date 1等價于date.toString() 1,但date - 1等價于date.valueOf() - 1。
您可能希望在兩種情況下都將時間戳記為數字,您可以通過手動呼叫.valueOf()它 ( date.valueOf() something) 或使用一元加號來實作,后者也僅適用于數字 ( date something)。
正如評論者安德烈亞斯指出:雖然這是答案的特定問題和誤解你了,整體更好的方法是使用moment的功能是,看到你反正已經使用該庫:moment().add(1, "d").startOf("day")明天0:00moment().add(28, "d")的4 周內一天中的同一時間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/391735.html
標籤:javascript 日期
