如何在今天之前三个月在 JavaScript 中计算日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7937233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I calculate the date in JavaScript three months prior to today?
提问by KeenUser
I Am trying to form a date which is 3 months before the current date. I get the current month by the below code
我试图形成一个比当前日期早 3 个月的日期。我通过以下代码获取当前月份
var currentDate = new Date();
var currentMonth = currentDate.getMonth()+1;
Can you guys provide me the logic to calculate and form a date (an object of the Date
data type) considering that when the month is January (1), 3 months before date would be OCtober (10)?
Date
考虑到当月份是一月 (1) 时,日期前 3 个月将是十月 (10),你们能否为我提供计算和形成日期(数据类型的对象)的逻辑?
回答by gilly3
var d = new Date();
d.setMonth(d.getMonth() - 3);
This works for January. Run this snippet:
这适用于一月。运行这个片段:
var d = new Date("January 14, 2012");
console.log(d.toLocaleDateString());
d.setMonth(d.getMonth() - 3);
console.log(d.toLocaleDateString());
There are some caveats...
有一些警告...
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. 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.
一个月是一件奇怪的事情。1个月怎么定义?30天?大多数人会说一个月前意味着上个月的同一天需要引用。但有一半以上的时间,即 31 天前,而不是 30 天。如果今天是本月的 31 日(不是八月或十二月),则该月的那一天在上个月不存在。
Interestingly, Google agrees with JavaScript if you ask it what day is one month before another day:
有趣的是,如果你问 Google在另一天之前的一个月是哪一天,Google 会同意 JavaScript :
It also says that one month is 30.4167 days long:
它还说一个月是 30.4167 天长:
So, is one month before March 31st the same day as one month before March 28th, 3 days earlier? This all depends on what you mean by "one month before". Go have a conversation with your product owner.
那么,3 月 31 日之前的一个月和 3 月 28 日之前的一个月是同一天,提前 3 天吗?这一切都取决于您所说的“一个月前”是什么意思。去和你的产品负责人谈谈。
If you want to do like momentjs does, and correct these last day of the month errors by moving to the last day of the month, you can do something like this:
如果你想像 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());
If your requirements are more complicated than that, use some math and write some code. You are a developer! You don't have to install a library! You don't have to copy and paste from stackoverflow! You can develop the code yourself to do precisely what you need!
如果您的要求比这更复杂,请使用一些数学方法并编写一些代码。你是开发者!您不必安装库!您不必从 stackoverflow 复制和粘贴!您可以自己开发代码来准确地做您需要的事情!
回答by Jan Osch
I recommend using a library called Moment.js.
我建议使用名为 Moment.js 的库。
It is well tested, works cross browser and on server side(I am using it both in Angular and Node projects). It has great support for locale dates.
它经过了很好的测试,可以跨浏览器和服务器端工作(我在 Angular 和 Node 项目中都使用它)。它对语言环境日期有很大的支持。
var threeMonthsAgo = moment().subtract(3, 'months');
console.log(threeMonthsAgo.format()); // 2015-10-13T09:37:35+02:00
.format()
returns string representation of date formatted in ISO 8601format. You can also use it with custom date format like this:.format('dddd, MMMM Do YYYY, h:mm:ss a')
.format()
返回以ISO 8601格式格式化的日期的字符串表示形式。您还可以将它与自定义日期格式一起使用,如下所示:.format('dddd, MMMM Do YYYY, h:mm:ss a')
回答by Hodeifa Baswel
This should handle addition/subtraction, just put a negative value in to subtract and a positive value to add. This also solves the month crossover problem.
这应该处理加法/减法,只需将负值放入减去并添加正值即可。这也解决了月份交叉问题。
function monthAdd(date, month) {
var temp = date;
temp = new Date(date.getFullYear(), date.getMonth(), 1);
temp.setMonth(temp.getMonth() + (month + 1));
temp.setDate(temp.getDate() - 1);
if (date.getDate() < temp.getDate()) {
temp.setDate(date.getDate());
}
return temp;
}
回答by thinkdevcode
To make things really simple you can use DateJS, a date library for JavaScript:
为了让事情变得非常简单,你可以使用 DateJS,一个 JavaScript 日期库:
Example code for you:
您的示例代码:
Date.today().add({ months: -1 });
回答by user7394313
A "one liner" (on many line for easy read)) to be put directly into a variable:
将直接放入变量的“单行”(在多行上以便于阅读):
var oneMonthAgo = new Date(
new Date().getFullYear(),
new Date().getMonth() - 1,
new Date().getDate()
);
回答by Niet the Dark Absol
If the setMonth
method offered by gilly3 isn't what you're looking for, consider:
如果setMonth
gilly3 提供的方法不是您要找的方法,请考虑:
var someDate = new Date(); // add arguments as needed
someDate.setTime(someDate.getTime() - 3*28*24*60*60);
// assumes the definition of "one month" to be "four weeks".
Can be used for any amount of time, just set the right multiples.
可以使用任何时间,只需设置正确的倍数。
回答by Don Kirkby
I like the simplicity of gilly3's answer, but users will probably be surprised that a month before March 31 is March 3. I chose to implement a version that sticks to the end of the month, so a month before March 28, 29, 30, and 31 will all be Feb 28 when it's not a leap year.
我喜欢gilly3的简单回答,但用户可能会感到惊讶,3月31日之前的一个月是3月3日。我选择了一个坚持到月底的版本,所以在3月28日、29日、30日之前的一个月, 31 将是 2 月 28 日,因为它不是闰年。
function addMonths(date, months) {
var result = new Date(date),
expectedMonth = ((date.getMonth() + months) % 12 + 12) % 12;
result.setMonth(result.getMonth() + months);
if (result.getMonth() !== expectedMonth) {
result.setDate(0);
}
return result;
}
var dt2004_05_31 = new Date("2004-05-31 0:00"),
dt2001_05_31 = new Date("2001-05-31 0:00"),
dt2001_03_31 = new Date("2001-03-31 0:00"),
dt2001_02_28 = new Date("2001-02-28 0:00"),
result = addMonths(dt2001_05_31, -2);
console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString());
result = addMonths(dt2001_05_31, -3);
console.assert(dt2001_02_28.getTime() == result.getTime(), result.toDateString());
result = addMonths(dt2001_05_31, 36);
console.assert(dt2004_05_31.getTime() == result.getTime(), result.toDateString());
result = addMonths(dt2004_05_31, -38);
console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString());
console.log('Done.');
回答by JamesD
There is an elegant answer already but I find that its hard to read so I made my own function. For my purposes I didn't need a negative result but it wouldn't be hard to modify.
已经有一个优雅的答案,但我发现它很难阅读,所以我制作了自己的函数。出于我的目的,我不需要负面结果,但修改起来并不难。
var subtractMonths = function (date1,date2) {
if (date1-date2 <=0) {
return 0;
}
var monthCount = 0;
while (date1 > date2){
monthCount++;
date1.setMonth(date1.getMonth() -1);
}
return monthCount;
}
回答by pooja
var d = new Date("2013/01/01");
console.log(d.toLocaleDateString());
d.setMonth(d.getMonth() + 18);
console.log(d.toLocaleDateString());
回答by Rohit Gaidhane
This is the Smallest and easiest code.
这是最小和最简单的代码。
var minDate = new Date();
minDate.setMonth(minDate.getMonth() - 3);
Declare variable which has current date. then just by using setMonth inbuilt function we can get 3 month back date.
声明具有当前日期的变量。然后只需使用 setMonth 内置函数,我们就可以获得 3 个月的回溯日期。