如果在Date中提供0作为dayValue。setFullYear你会得到上个月的最后一天:
d = new Date(); d.setFullYear(2008, 11, 0); // Sun Nov 30 2008
在mozilla中有这种行为的参考。这是一个可靠的跨浏览器功能吗?或者我应该看看其他的方法吗?
如果在Date中提供0作为dayValue。setFullYear你会得到上个月的最后一天:
d = new Date(); d.setFullYear(2008, 11, 0); // Sun Nov 30 2008
在mozilla中有这种行为的参考。这是一个可靠的跨浏览器功能吗?或者我应该看看其他的方法吗?
当前回答
对lebreeze提供的解决方案稍加修改:
function daysInMonth(iMonth, iYear)
{
return new Date(iYear, iMonth, 0).getDate();
}
其他回答
试试这个。
lastDateofTheMonth = new Date(year, month, 0)
例子:
new Date(2012, 8, 0)
输出:
Date {Fri Aug 31 2012 00:00:00 GMT+0900 (Tokyo Standard Time)}
我将使用一个中间日期与下个月的第一天,并返回前一天的日期:
int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);
我觉得这对我来说是最好的解决办法。让Date对象为您计算它。
var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);
将day参数设置为0表示比本月的第一天小一天,即上个月的最后一天。
公认的答案不适合我,我是这样做的。
$( function() { $( "#datepicker" ).datepicker(); $('#getLastDateOfMon').on('click', function(){ var date = $('#datepicker').val(); // Format 'mm/dd/yy' eg: 12/31/2018 var parts = date.split("/"); var lastDateOfMonth = new Date(); lastDateOfMonth.setFullYear(parts[2]); lastDateOfMonth.setMonth(parts[0]); lastDateOfMonth.setDate(0); alert(lastDateOfMonth.toLocaleDateString()); }); }); <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <p>Date: <input type="text" id="datepicker"></p> <button id="getLastDateOfMon">Get Last Date of Month </button> </body> </html>
对我来说,这段代码很有用
end_date = new Date(2018, 3,1).toISOString().split('T')[0] console.log (end_date)