简体   繁体   English

计算一个月的最后一天

[英]Calculate last day of month

If you provide 0 as the dayValue in Date.setFullYear you get the last day of the previous month:如果您在Date.setFullYear中提供0作为dayValue ,您将获得上个月的最后一天:

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

There is reference to this behaviour at mozilla .mozilla中提到了这种行为。 Is this a reliable cross-browser feature or should I look at alternative methods?这是一个可靠的跨浏览器功能还是我应该看看其他方法?

 var month = 0; // January var d = new Date(2008, month + 1, 0); console.log(d.toString()); // last day in January

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)

Output differences are due to differences in the toString() implementation, not because the dates are different.输出差异是由于toString()实现的差异,而不是因为日期不同。

Of course, just because the browsers identified above use 0 as the last day of the previous month does not mean they will continue to do so, or that browsers not listed will do so, but it lends credibility to the belief that it should work the same way in every browser. 当然,仅仅因为上面确定的浏览器使用 0 作为上个月的最后一天并不意味着它们会继续这样做,或者没有列出的浏览器会这样做,但它增加了人们相信它应该可以工作的可信度。在每个浏览器中都以相同的方式。

I find this to be the best solution for me.我发现这对我来说是最好的解决方案。 Let the Date object calculate it for you.让 Date 对象为您计算它。

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

Setting day parameter to 0 means one day less than first day of the month which is last day of the previous month.将 day 参数设置为 0 表示比该月的第一天少一天,即上个月的最后一天。

I would use an intermediate date with the first day of the next month, and return the date from the previous day:我会在下个月的第一天使用中间日期,并返回前一天的日期:

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

In computer terms, new Date() and regular expression solutions are slow!用计算机术语来说, new Date()regular expression解决方案很慢! If you want a super-fast (and super-cryptic) one-liner, try this one (assuming m is in Jan=1 format).如果你想要一个超快速(和超神秘)的单行,试试这个(假设mJan=1格式)。 I keep trying different code changes to get the best performance.我不断尝试不同的代码更改以获得最佳性能。

My current fastest version:我目前最快的版本:

After looking at this related question Leap year check using bitwise operators (amazing speed) and discovering what the 25 & 15 magic number represented, I have come up with this optimized hybrid of answers:在查看了这个相关的问题Leap year check using bitwise operators (惊人的速度)并发现了 25 & 15 幻数代表什么之后,我想出了这个优化的混合答案:

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

Given the bit-shifting this obviously assumes that your m & y parameters are both integers, as passing numbers as strings would result in weird results.考虑到位移,这显然假设您的my参数都是整数,因为将数字作为字符串传递会导致奇怪的结果。

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

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

For some reason, (m+(m>>3)&1) is more efficient than (5546>>m&1) on almost all browsers.由于某种原因, (m+(m>>3)&1) 1) 在几乎所有浏览器上都比(5546>>m&1)更有效。

The only real competition for speed is from @GitaarLab, so I have created a head-to-head JSPerf for us to test on: http://jsperf.com/days-in-month-head-to-head/5唯一真正的速度竞争来自@GitaarLab,所以我创建了一个面对面的 JSPerf 供我们测试:http: //jsperf.com/days-in-month-head-to-head/5


It works based on my leap year answer here: javascript to find leap year this answer here Leap year check using bitwise operators (amazing speed) as well as the following binary logic.它基于我的闰年答案在这里工作: javascript to findleap year this answer here 闰年检查使用按位运算符(惊人的速度)以及以下二进制逻辑。

A quick lesson in binary months:二进制月份的快速课程:

If you interpret the index of the desired months (Jan = 1) in binary you will notice that months with 31 days either have bit 3 clear and bit 0 set, or bit 3 set and bit 0 clear.如果您以二进制形式解释所需月份的索引(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

That means you can shift the value 3 places with >> 3 , XOR the bits with the original ^ m and see if the result is 1 or 0 in bit position 0 using & 1 .这意味着您可以使用>> 3将值移位 3 位,使用原始^ m对位进行异或运算,并使用& 1查看位位置 0 中的结果是1还是0 Note: It turns out + is slightly faster than XOR ( ^ ) and (m >> 3) + m gives the same result in bit 0.注意:事实证明+比 XOR ( ^ ) 稍快, (m >> 3) + m在位 0 中给出相同的结果。

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

My colleague stumbled upon the following which may be an easier solution我的同事偶然发现了以下可能是更简单的解决方案

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

stolen from http://snippets.dzone.com/posts/show/2099从 http://snippets.dzone.com/posts/show/2099 被盗

A slight modification to solution provided by lebreeze :lebreeze提供的解决方案稍作修改:

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

I recently had to do something similar, this is what I came up with:我最近不得不做类似的事情,这就是我想出的:

/**
* 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;
}

Pass it in a date, and it will return a date set to either the beginning of the month, or the end of the month.将它传入一个日期,它将返回一个设置为月初或月底的日期。

The begninngOfMonth function is fairly self-explanatory, but what's going in in the endOfMonth function is that I'm incrementing the month to the next month, and then using setDate(0) to roll back the day to the last day of the previous month which is a part of the setDate spec: 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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate https://www.w3schools.com/jsref/jsref_setdate.asp

I then set the hour/minutes/seconds to the end of the day, so that if you're using some kind of API that is expecting a date range you'll be able to capture the entirety of that last day.然后,我将小时/分钟/秒设置为一天结束,这样,如果您使用某种 API 预期日期范围,您将能够捕获最后一天的全部内容。 That part might go beyond what the original post is asking for but it could help someone else looking for a similar solution.这部分可能超出了原始帖子的要求,但它可以帮助其他人寻找类似的解决方案。

Edit: You can also go the extra mile and set milliseconds with setMilliseconds() if you want to be extra precise.编辑:如果您想更加精确,您也可以加倍努力并使用setMilliseconds()设置毫秒。

try this one.试试这个。

lastDateofTheMonth = new Date(year, month, 0)

example:例子:

new Date(2012, 8, 0)

output:输出:

Date {Fri Aug 31 2012 00:00:00 GMT+0900 (Tokyo Standard Time)}

This works for me.这对我有用。 Will provide last day of given year and month:将提供给定年份和月份的最后一天:

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

How NOT to do it如何不做

Beware of any answers for the last of the month that look like this:请注意本月最后一个看起来像这样的任何答案:

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

This works for most dates, but fails if date is already the last day of the month, on a month that has more days than the following month.这适用于大多数日期,但如果date已经是该月的最后一天,并且该月的天数比下个月的天数多,则会失败。

Example:例子:

Suppose date is 07/31/21 .假设date07/31/21

Then last.setMonth(last.getMonth() + 1) increments the month, but keeps the day set at 31 .然后last.setMonth(last.getMonth() + 1)增加月份,但将日期设置为31

You get a Date object for 08/31/21 ,你得到一个08/31/21的 Date 对象,

which is actually 09/01/21 .实际上是09/01/21

So then last.setDate(0) results in 08/31/21 when what we really wanted was 07/31/21 .那么last.setDate(0)结果是08/31/21而我们真正想要的是07/31/21

This one works nicely:这个很好用:

Date.prototype.setToLastDateInMonth = function () {

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

    return this;
}

This will give you current month first and last day.这将为您提供当前月份的第一天和最后一天。

If you need to change 'year' remove d.getFullYear() and set your year.如果您需要更改“年份”,请删除 d.getFullYear() 并设置您的年份。

If you need to change 'month' remove d.getMonth() and set your year.如果您需要更改“月份”,请删除 d.getMonth() 并设置您的年份。

 var d = new Date(); var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var fistDayOfMonth = days[(new Date(d.getFullYear(), d.getMonth(), 1).getDay())]; var LastDayOfMonth = days[(new Date(d.getFullYear(), d.getMonth() + 1, 0).getDay())]; console.log("First Day :" + fistDayOfMonth); console.log("Last Day:" + LastDayOfMonth); alert("First Day :" + fistDayOfMonth); alert("Last Day:" + LastDayOfMonth);

Try this:尝试这个:

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

You can get the First and Last Date in the current month by following the code:您可以通过以下代码获取当月的第一个和最后一个日期:

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

or if you want to format the date in your custom format then you can use moment js或者如果您想以自定义格式格式化日期,那么您可以使用 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

Below function gives the last day of the month :下面的函数给出了该月的最后一天:

 function getLstDayOfMonFnc(date) { return new Date(date.getFullYear(), date.getMonth(), 0).getDate() } console.log(getLstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 29 console.log(getLstDayOfMonFnc(new Date(2017, 2, 15))) // Output : 28 console.log(getLstDayOfMonFnc(new Date(2017, 11, 15))) // Output : 30 console.log(getLstDayOfMonFnc(new Date(2017, 12, 15))) // Output : 31

Similarly we can get first day of the month :同样,我们可以得到该月的第一天:

 function getFstDayOfMonFnc(date) { return new Date(date.getFullYear(), date.getMonth(), 1).getDate() } console.log(getFstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 1

Here is an answer that conserves GMT and time of the initial date这是一个保存 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);
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)); 
}

set month you need to date and then set the day to zero ,so month begin in 1 - 31 in date function then get the last day^^设置您需要约会的月份,然后将日期设置为零,因此月份在日期函数中从 1 - 31 开始,然后获取最后一天^^

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

I know it's just a matter of semantics, but I ended up using it in this form.我知道这只是语义问题,但我最终以这种形式使用它。

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

Since functions are resolved from the inside argument, outward, it works the same.由于函数是从内部参数向外解析的,因此它的工作原理相同。

You can then just replace the year, and month / year with the required details, whether it be from the current date.然后,您可以用所需的详细信息替换年和月/年,无论它是从当前日期开始的。 Or a particular month / year.或特定的月份/年份。

If you need exact end of the month in miliseconds (for example in a timestamp):如果您需要以毫秒为单位的确切月底(例如时间戳):

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

The accepted answer doesn't work for me, I did it as below.接受的答案对我不起作用,我做了如下。

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

This will give you last day of current month.这将为您提供当前月份的最后一天。

notes: on ios device include time .注意:在 ios 设备上包括时间 #gshoanganh #gshoanganh

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

if you just need to get the last date of a month following worked out for me.如果您只需要为我计算出一个月的最后一个日期。

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

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

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

In my case, this code was useful就我而言,这段代码很有用

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

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

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