如何在 JavaScript 中计算今天之前三个月的日期?

2024-05-25

我正在尝试确定当前日期之前 3 个月的日期。我通过下面的代码获取当前月份

var currentDate = new Date();
var currentMonth = currentDate.getMonth()+1;

你们能给我提供计算和形成日期的逻辑(日期的对象吗?Date数据类型)考虑到月份为 1 月 (1) 时,日期前 3 个月为 10 月 (10)?


var d = new Date();
d.setMonth(d.getMonth() - 3);

这适用于一月份。运行这个片段:

var d = new Date("January 14, 2012");
console.log(d.toLocaleDateString());
d.setMonth(d.getMonth() - 3);
console.log(d.toLocaleDateString());

有一些注意事项...

A month is a curious thing. How do you define 1 month? 30 days? Most people will say that one month ago means the same day of the month on the previous month citation needed https://xkcd.com/285/. But more than half the time, that is 31 days ago, not 30. And if today is the 31st of the month (and it isn't August or Decemeber), that day of the month doesn't exist in the previous month.

有趣的是,如果你问的话,Google 会同意 JavaScript一个月前的哪一天是另一天 https://www.google.com/search?q=one+month+before+March+31+1995:

It also says that one month is 30.4167 days long https://www.google.com/search?q=one+month+in+days: Google search result for 'one month in days' shows '30.4167'

那么,3月31日之前一个月与3月28日之前一个月是同一天,提前3天吗?这完全取决于你所说的“一个月前”是什么意思。去和你的产品负责人谈谈。

如果您想像 momentjs 那样,并通过移动到该月的最后一天来纠正这些月份最后一天的错误,您可以执行以下操作:

const d = new Date("March 31, 2019");
console.log(d.toLocaleDateString());
const month = d.getMonth();
d.setMonth(d.getMonth() - 1);
while (d.getMonth() === month) {
    d.setDate(d.getDate() - 1);
}
console.log(d.toLocaleDateString());

如果您的要求比这更复杂,请使用一些数学知识并编写一些代码。你是一个开发者!您不必安装库!您不必从 stackoverflow 复制并粘贴!您可以自己开发代码来精确地完成您需要的操作!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 JavaScript 中计算今天之前三个月的日期? 的相关文章

随机推荐