【发布时间】:2022-01-23 18:59:10
【问题描述】:
此代码减去日期:
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早一天。
知道这里发生了什么吗?
【问题讨论】:
-
为什么只使用momentjs进行格式化? o.O
标签: javascript date