简体   繁体   English

上个月最后一天的javascript日期

[英]javascript date of last day of previous month

Let's say I have 3 variables like this:假设我有 3 个这样的变量:

var Month = 8; // in reality, it's a parameter provided by some user input
var Year = 2011; // same here
var FirstDay = new Date(Year, Month, 1);

Now I want to have the value of the day before the first day of the month in a variable.现在我想在变量中包含一个月的第一天之前的一天的值。 I'm doing this:我这样做:

var LastDayPrevMonth = (FirstDay.getDate() - 1);

It's not working as planned.它没有按计划工作。 What the right of doing it?有什么权利这样做?

Thanks.谢谢。

var LastDayPrevMonth = new Date(Year, Month, 0).getDate();
var LastDayPrevMonth = new Date(FirstDay);
LastDayPrevMonth.setHours(FirstDay.getHours()-24);

If you need to calculate this based on today's date ( you want the last day of last month ), the following should help.如果您需要根据今天的日期(您想要上个月的最后一天)来计算它,以下内容应该会有所帮助。

If you only care about the month/day/year, this is the simplest and fastest that I can think of:如果你只关心月/日/年,这是我能想到的最简单最快的:

var d = new Date(); d.setDate(0);
console.log(d);

If you want midnight of last day of the previous month, then:如果您想要上个月最后一天的午夜,则:

var d = new Date(); d.setDate(0); d.setHours(0,0,0,0);
console.log(d);

If you want to know the last day of the previous month, based on provided year/month:如果您想根据提供的年/月知道上个月的最后一天:

var year = 2016, month = 11;
var d = new Date(year, (month - 1)); d.setDate(0); d.setHours(0,0,0,0);
console.log(d);

After running any of the above, to get the YYYY-MD format:运行上述任何一项后,获取 YYYY-MD 格式:

var str = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
console.log(str);

To see additional methods available, and to see what they do, you can read the docs .要查看可用的其他方法并查看它们的作用,您可以阅读 docs

Create a new Date object and pass it the other date coerced to the number of milliseconds since the Unix epoch and then minus a whole day (in milliseconds).创建一个新的Date对象并将另一个日期传递给它,该日期强制为自Unix 纪元以来的毫秒数,然后减去一整天(以毫秒为单位)。

var LastDayPrevMonth = new Date(FirstDay - 864e5);

Example:例子:

 var Month = 8; // in reality, it's a parameter provided by some user input var Year = 2011; // same here var FirstDay = new Date(Year, Month, 1); var LastDayPrevMonth = new Date(FirstDay - 864e5); document.body.innerHTML = LastDayPrevMonth;

var FirstDay = new Date(Year, Month, 1);
var lastMonth = new Date(FirstDay);
lastMonth.setDate(-1);
alert(lastMonth);

And remember that 8 is Sept, not Aug in JavaScript.请记住,8 是九月,而不是 JavaScript 中的八月。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM