Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中获取上一个月/上一个月的最后一天_Javascript_Date - Fatal编程技术网

在javascript中获取上一个月/上一个月的最后一天

在javascript中获取上一个月/上一个月的最后一天,javascript,date,Javascript,Date,我正在使用以下代码,其中月份是当前月份(我在哪里): 这个想法是,如果我在一年的第一个月,前一个月就是前一年的最后一个月 如果我在2018年1月,报告2017年12月的最后一天是30天,这不是真的,是31天,但我不知道为什么。下面也给出了你想要的结果 var LastDay = new Date(year-1, 12, 0); //new Date(year - 1, 11, 0).getDate() this line seems issue in your code 这张是我2017年

我正在使用以下代码,其中月份是当前月份(我在哪里):

这个想法是,如果我在一年的第一个月,前一个月就是前一年的最后一个月


如果我在2018年1月,报告2017年12月的最后一天是30天,这不是真的,是31天,但我不知道为什么。

下面也给出了你想要的结果

var LastDay =  new Date(year-1, 12, 0);
//new Date(year - 1, 11, 0).getDate() this line seems issue in your code

这张是我2017年12月31日回来的

 var month = 0;//this you will get when do dt.getMonth() in January month
 var year = 2018;           
 var LastDay = new Date(year, month, 0);

document.getElementById("demo").innerHTML = LastDay;

试试这个对我有用

 var dt = new Date();
 var month = dt.getMonth();
 var year = 2018;

 var LastDay = new Date(year, month, 0);

 console.log(LastDay);
请尝试以下方法:

lastDayOfLastMonth = month === 0 ? new Date(year - 1, 12, 0).getDate(): 
                                   new Date(year, month, 0).getDate();

Date
构造函数的日期部分不是0索引的,而是当月的实际日期。在您的第一个条件中,
新日期(年份-1,11,0).getDate()
,您将首先将日期初始化为2017年12月0日。建造商随后将其更正为2017年11月30日

如果想要上个月的最后一天,可以忽略三元运算符并执行以下操作,因为
Date
构造函数将进行必要的转换:

lastDayOfLastMonth = new Date(currentYear, currentMonth, 0).getDate();

请注意,
currentMonth
仍为0索引(即1月为0月,12月为11月)

这对您有效吗?简要说明代码的作用将是一个很好的改进。考虑为OP和社区增加一个
lastDayOfLastMonth = month === 0 ? new Date(year - 1, 12, 0).getDate(): 
                                   new Date(year, month, 0).getDate();
lastDayOfLastMonth = new Date(currentYear, currentMonth, 0).getDate();