Javascript - 从当前日期计算上个月

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11949191/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:51:16  来源:igfitidea点击:

Javascript - Previous month computation from a current date

javascript

提问by Programmer

I have a below JS where I get the max date that is user allowed to enter from a backend script:

我有一个下面的 JS,在那里我获得了允许用户从后端脚本输入的最大日期:

var max_date = new Date(pdate + " " + ptime);

where pdate and ptime is fetched from a script.

其中 pdate 和 ptime 是从脚本中获取的。

Now I need to set the min date as 1 month less than max_date

现在我需要将最小日期设置为比 max_date 少 1 个月

if (max_date.getMonth() == 0)
subtractyear = 1;
var min_date = new Date(Date.UTC(max_date.getFullYear() - subtractyear,max_date.getMonth() - 1,max_date.getDate(),max_date.getHours(),0,0));

My issue is that if max_date is March 31 - then will the min_date be rolled over to Feb 28 or Feb 29 or Feb 31 or Feb 30?

我的问题是,如果 max_date 是 3 月 31 日 - 那么 min_date 是否会滚动到 2 月 28 日或 2 月 29 日或 2 月 31 日或 2 月 30 日?

If the date formed is an incorrect date - say Feb 30 how can I rectify this?

如果形成的日期不正确 - 比如说 2 月 30 日,我该如何纠正?

回答by otakustay

Simple subject the month by 1 would get a valid date -- never would setMonthmethod return an invalid Dateobject (the same as setDate, setYearand the Dateconstructor):

1 月份的简单主题将获得有效日期——setMonth方法永远不会返回无效Date对象(与setDate,setYearDate构造函数相同):

var date = new Date(2012, 02, 31); // 2012-03-31
date.setMonth(date.getMonth() - 1); // This gets 2012-03-02

I don't quite clear what date you expected, the last day of the previous monthor just the day one month earlier?

我不太清楚你预计的日期是上个月的最后一天还是一个月前的一天