如果在Date中提供0作为dayValue。setFullYear你会得到上个月的最后一天:

d = new Date(); d.setFullYear(2008, 11, 0); //  Sun Nov 30 2008

在mozilla中有这种行为的参考。这是一个可靠的跨浏览器功能吗?或者我应该看看其他的方法吗?


我将使用一个中间日期与下个月的第一天,并返回前一天的日期:

int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);

Var月= 0;/ / 1月 var d = new日期(2008,月份+ 1,0); console.log (d.toString ());// 1月的最后一天

IE 6:                     Thu Jan 31 00:00:00 CST 2008
IE 7:                     Thu Jan 31 00:00:00 CST 2008
IE 8: Beta 2:             Thu Jan 31 00:00:00 CST 2008
Opera 8.54:               Thu, 31 Jan 2008 00:00:00 GMT-0600
Opera 9.27:               Thu, 31 Jan 2008 00:00:00 GMT-0600
Opera 9.60:               Thu Jan 31 2008 00:00:00 GMT-0600
Firefox 2.0.0.17:         Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Firefox 3.0.3:            Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Google Chrome 0.2.149.30: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Safari for Windows 3.1.2: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)

输出差异是由于toString()实现的差异,而不是由于日期不同。

当然,仅仅因为上面列出的浏览器使用0作为上个月的最后一天并不意味着它们会继续这样做,或者没有列出的浏览器会这样做,但它使人们相信它应该在每个浏览器中以相同的方式工作。


我的同事偶然发现了以下可能是一个更简单的解决方案

function daysInMonth(iMonth, iYear)
{
    return 32 - new Date(iYear, iMonth, 32).getDate();
}

窃取自http://snippets.dzone.com/posts/show/2099


对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)}

我觉得这对我来说是最好的解决办法。让Date对象为您计算它。

var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);

将day参数设置为0表示比本月的第一天小一天,即上个月的最后一天。


在计算机术语中,新的Date()和正则表达式解决方案很慢!如果您想要一个超级快速(并且超级神秘)的一行程序,可以试试这个(假设m的格式是Jan=1)。我不断尝试不同的代码更改以获得最佳性能。

我目前最快的版本是:

在使用位运算符(惊人的速度)查看闰年检查相关问题并发现25和15的神奇数字所代表的含义后,我提出了这个优化的混合答案(注意参数m和y显然必须是整数才能工作):

function getDaysInMonth(m, y) {
    return m===2 ? y & 3 || !(y%25) && y & 15 ? 28 : 29 : 30 + (m+(m>>3)&1);
}

考虑到位移位,这显然假设m和y参数都是整数,因为将数字作为字符串传递会导致奇怪的结果。

JSFiddle: http://jsfiddle.net/TrueBlueAussie/H89X3/22/

JSPerf结果:http://jsperf.com/days-in-month-head-to-head/5

由于某种原因,在几乎所有浏览器上(m+(m>>3)&1)都比(5546>>m&1)更有效。

唯一真正的速度竞争来自@GitaarLab,所以我创建了一个直接的JSPerf供我们测试:http://jsperf.com/days-in-month-head-to-head/5


它的工作基于我的闰年答案在这里:javascript找到闰年这个答案在这里闰年检查使用位运算符(惊人的速度)以及以下二进制逻辑。

用二进制月份快速学习一下:

如果您以二进制形式解释所需月份(Jan = 1)的索引,您会注意到有31天的月份要么有第3位清除和第0位设置,要么有第3位设置和第0位清除。

Jan = 1  = 0001 : 31 days
Feb = 2  = 0010
Mar = 3  = 0011 : 31 days
Apr = 4  = 0100
May = 5  = 0101 : 31 days
Jun = 6  = 0110
Jul = 7  = 0111 : 31 days
Aug = 8  = 1000 : 31 days
Sep = 9  = 1001
Oct = 10 = 1010 : 31 days
Nov = 11 = 1011
Dec = 12 = 1100 : 31 days

这意味着你可以用>> 3将值移动3个位置,用原来的^ m对位进行异或,并使用& 1查看位位置0的结果是1还是0。注意:结果是+比XOR(^)略快,(m >> 3) + m在位0中给出相同的结果。

JSPerf结果:http://jsperf.com/days-in-month-perf-test/6


function getLastDay(y, m) {
   return 30 + (m <= 7 ? ((m % 2) ? 1 : 0) : (!(m % 2) ? 1 : 0)) - (m == 2) - (m == 2 && y % 4 != 0 || !(y % 100 == 0 && y % 400 == 0)); 
}

这对我很有用。 将提供给定年份和月份的最后一天:

var d = new Date(2012,02,0);
var n = d.getDate();
alert(n);

这个很好用:

Date.prototype.setToLastDateInMonth = function () {

    this.setDate(1);
    this.setMonth(this.getMonth() + 1);
    this.setDate(this.getDate() - 1);

    return this;
}

设置你需要日期的月份,然后将日期设置为0,所以在date函数中,月份从1 - 31开始,然后得到最后一天^^

var last = new Date(new Date(new Date().setMonth(7)).setDate(0)).getDate(); console.log(去年);


我知道这只是一个语义问题,但我最终以这种形式使用它。

var lastDay = new Date(new Date(2008, 11+1,1) - 1).getDate();
console.log(lastDay);

因为函数是从内部参数向外解析的,所以工作原理是一样的。

然后,您可以用所需的详细信息替换年和月/年,无论它来自当前日期。或者一个特定的月/年。


下面的函数给出了这个月的最后一天:

函数getLstDayOfMonFnc(date) { 返回new Date(Date . getfullyear (), Date . getmonth (), 0).getDate() } console.log(getLstDayOfMonFnc(new Date(2016, 2,15))) //输出:29 console.log(getLstDayOfMonFnc(new Date(2017,2,15))) //输出:28 console.log(getLstDayOfMonFnc(new Date(2017,11,15))) //输出:30 console.log(getLstDayOfMonFnc(new Date(2017,12,15))) //输出:31

类似地,我们可以得到这个月的第一天:

函数getFstDayOfMonFnc(日期){ 返回new Date(Date . getfullyear (), Date . getmonth (), 1).getDate() } console.log(getFstDayOfMonFnc(new Date(2016, 2,15))) //输出


这将给出本月的第一天和最后一天。

如果你需要改变“年份”,删除d.getFullYear()并设置你的年份。

如果需要更改“month”,则删除d.getMonth()并设置年份。

var = new Date() 瓦尔日=[“星期日”、“星期一”、“星期二”、“星期三”、“星期五”、“星期六”]; var fistdaymoon = day[(新日期[d. getllyear], d.getMonth(), 1 .getDay [) var lastyousmonth = day[(新日期[d.getFullYear], d.getMonth() + 1, 0).getDay() 控制台(“第一天: 控制台(“最后一天:” 警告(“第一天:”+“嘶嘶声”); 警告(“最后一天:”+ lastdamonth);


我最近不得不做一些类似的事情,这是我想到的:

/**
* Returns a date set to the begining of the month
* 
* @param {Date} myDate 
* @returns {Date}
*/
function beginningOfMonth(myDate){    
  let date = new Date(myDate);
  date.setDate(1)
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);   
  return date;     
}

/**
 * Returns a date set to the end of the month
 * 
 * @param {Date} myDate 
 * @returns {Date}
 */
function endOfMonth(myDate){
  let date = new Date(myDate);
  date.setDate(1); // Avoids edge cases on the 31st day of some months
  date.setMonth(date.getMonth() +1);
  date.setDate(0);
  date.setHours(23);
  date.setMinutes(59);
  date.setSeconds(59);
  return date;
}

向它传递一个日期,它将返回一个设置为月初或月底的日期。

begninngOfMonth函数是相当不言自明的,但是endOfMonth函数中的内容是,我将这个月递增到下个月,然后使用setDate(0)将前一天回滚到上个月的最后一天,这是setDate规范的一部分:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate https://www.w3schools.com/jsref/jsref_setdate.asp

然后我将小时/分/秒设置为一天的结束,这样如果您正在使用某种期望日期范围的API,您将能够捕获最后一天的全部内容。这部分内容可能超出了最初帖子的要求,但它可以帮助其他人寻找类似的解决方案。

编辑:如果您想要更加精确,还可以使用setMilliseconds()额外设置毫秒。


试试这个:

function _getEndOfMonth(time_stamp) {
    let time = new Date(time_stamp * 1000);
    let month = time.getMonth() + 1;
    let year = time.getFullYear();
    let day = time.getDate();
    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            day = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            day = 30;
            break;
        case 2:
            if (_leapyear(year))
                day = 29;
            else
                day = 28;
            break
    }
    let m = moment(`${year}-${month}-${day}`, 'YYYY-MM-DD')
    return m.unix() + constants.DAY - 1;
}

function _leapyear(year) {
    return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
}

下面是一个保留GMT时间和初始日期时间的答案

var date = new Date(); var first_date = new Date(date); //Make a copy of the date we want the first and last days from first_date.setUTCDate(1); //Set the day as the first of the month var last_date = new Date(first_date); //Make a copy of the calculated first day last_date.setUTCMonth(last_date.getUTCMonth() + 1); //Add a month last_date.setUTCDate(0); //Set the date to 0, this goes to the last day of the previous month console.log(first_date.toJSON().substring(0, 10), last_date.toJSON().substring(0, 10)); //Log the dates with the format yyyy-mm-dd


const today = new Date();

let beginDate = new Date();

let endDate = new Date();

// fist date of montg

beginDate = new Date(

  `${today.getFullYear()}-${today.getMonth() + 1}-01 00:00:00`

);

// end date of month 

// set next Month first Date

endDate = new Date(

  `${today.getFullYear()}-${today.getMonth() + 2}-01 :23:59:59`

);

// deducting 1 day

endDate.setDate(0);

如果你需要精确的以毫秒为单位的月底(例如时间戳):

d = new Date() console.log (d.toString ()) d.setDate (1) d.setHours(23, 59, 59, 999) d.setMonth(d.getMonth() + 1) d.setDate(d.getDate() - 1) console.log (d.toString ())


公认的答案不适合我,我是这样做的。

$( 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>


你可以通过下面的代码获取当月的第一个和最后一个日期:

var dateNow = new Date();  
var firstDate = new Date(dateNow.getFullYear(), dateNow.getMonth(), 1);  
var lastDate = new Date(dateNow.getFullYear(), dateNow.getMonth() + 1, 0);

或者如果你想用自定义格式格式化日期,那么你可以使用moment js

var dateNow= new Date();  
var firstDate=moment(new Date(dateNow.getFullYear(),dateNow.getMonth(), 1)).format("DD-MM-YYYY");  
var currentDate = moment(new Date()).format("DD-MM-YYYY"); //to  get the current date var lastDate = moment(new
 Date(dateNow.getFullYear(), dateNow.getMonth() + 1, 0)).format("DD-MM-YYYY"); //month last date

这将给你当月的最后一天。

注:在ios设备上包含时间。 # gshoanganh

var date = new Date();
console.log(new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59));

如果你只需要得到一个月的最后一个日期,下面的工作为我。

var d = new Date();
const year = d.getFullYear();
const month = d.getMonth();

const lastDay =  new Date(year, month +1, 0).getDate();
console.log(lastDay);

在这里试试https://www.w3resource.com/javascript-exercises/javascript-date-exercise-9.php


如何不这样做

这个月最后一个月的答案可能是这样的:

var last = new Date(date)
last.setMonth(last.getMonth() + 1) // This is the wrong way to do it.
last.setDate(0)

这适用于大多数日期,但如果日期已经是该月的最后一天,而该月的天数比下一个月多,则会失败。

例子:

假设日期是07/31/21。

然后last.setMonth(last.getMonth() + 1)增加月份,但保持日期设置为31。

你得到08/31/21的Date对象,

实际上是21年9月1日。

所以last.setDate(0)的结果是08/31/21,而我们真正想要的是07/31/21。


对我来说,这段代码很有用

end_date = new Date(2018, 3,1).toISOString().split('T')[0] console.log (end_date)