简体   繁体   English

Javascript / jQuery:如何检查日期是否为每月的最后一天

[英]Javascript / jQuery: How to check if date is last day of month

I have the following code (shortened) which creates the dates of a month while looping through an array. 我有以下代码(缩短了),它在遍历数组时创建一个月的日期。

This works fine so far but I am struggling to stop it if it reaches the last day of a month . 到目前为止, 它仍然可以正常工作,但是如果它到了一个月的最后一天,我将竭力阻止它 I am using this to dynamically add table rows to an HTML table and as the array is set to end at 31 it always starts with the next month when the set month has less than 31 days. 我正在使用它动态地向HTML表添加表行,并且由于数组设置为以31结尾,因此当设置的月份少于31天时,数组总是从下个月开始。 The cells in my table then show eg ... 28, 29, 1, 2 for the February column. 然后,我表中的单元格在28, 29, 1, 2月列中显示了例如... 28、29、1、2。

Can someone tell me how I can check whether day1 , day2 or day3 are the last day of the month and if set them to '' ? 有人可以告诉我如何检查day1day2day3是月份的最后一天,并将它们设置为吗?

My thought was that the following will give me the last day of a month but I couldn't find a way to work this in here and to use it properly for the comparisons: 我的想法是,以下内容将给我一个月的最后一天,但是我找不到在这里进行操作并将其正确用于比较的方法:

var d = new Date(y, m+1, 0);

My JS (shortened): 我的JS(简称):

$('#btnStart').on('click', function(){
    var date1, day1;
    var date2, day2;            

    var d = 0;
    var m = 0;  // user input
    var y = 2015; // user input
    for (d = 0; d <= 30; d++) {
        date1 = new Date(y, m, d+1);
        day1 = date1.getDate();
        date2 = new Date(y, m+1, d+1);
        day2 = date2.getDate();
    }
});

Update: This is only needed within a given year so it will never go from December to January. 更新:这仅在给定年份内需要,因此它将永远不会从12月到1月。

Many thanks for any help with this, Mike 非常感谢您对此提供的帮助,迈克

If you add one day to the date, and the resulting date is the first of next month, then the examined date was the last day of its month. 如果您将日期添加一天,并且结果日期是下个月的第一天,则检查的日期是该月的最后一天。

something like 就像是

isLast = (new Date(examinedDate.getTime() + 24*60*60*1000).getDate()) === 1

Add this in your For loop 在您的For循环中添加

if(day2 < day1)
    break;

with a simple function perhaps: 一个简单的功能也许:

function isLastDay(y, m, d)
{
    var d1 = (m < 11) ? new Date(y, m + 1, 0) : new Date(y, 0, 0);
    var d2 = new Date(y, m, d);
    return (d1.getTime() === d2.getTime());
}

You should use date.getTime() to compare dates. 您应该使用date.getTime()来比较日期。

Working jsbin with your example code: 使用示例代码运行jsbin:

http://jsbin.com/puhuvirize/2/edit?js,output http://jsbin.com/puhuvirize/2/edit?js,output

This will give you the last day of month 'm': 这将为您提供月份“ m”的最后一天:

new Date(y, m + 1, 0)

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

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