JavaScript 验证日期并返回日历的最后可用日期



如果日期不在日历中退出,我想验证我的日期,然后返回历的最后可用日期,

例 01

Input Date    : 31-Feb-2017 
Return Result : 28-Feb-2017

例子 02

Input Date    : 31-March-2017
Return Result : 31-March-2017

例子 03

Input Date    : 31-Apr-2017
Return Result : 30-Apr-2017

例子 04

Input Date    : 31-Jun-2017
Return Result : 30-Jun-2017

示例 05 与叶年

Input Date    : 31-Feb-2020 
Return Result : 29-Feb-2020

这是我第一次尝试使用以下函数验证日期,如何为上述日期制作逻辑。

function isValidDate(year, month, day) {
    var d = new Date(year, month, day);
    if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
        return true;
    }
    return false;
}

该月的最后一天由下个月的零天给出,因此:

function getDate(year, month, day) {
    var d = new Date(year, month, day);
    if (d.getMonth() == month) {
        return d;
    }
    return new Date(year, +month + 1, 0);
}
console.log(getDate(2017,1,29).toString());
console.log(getDate(2017,0,32).toString());

顺便说一句,要测试有效日期,您只需要测试月份,因为如果月份大于一年中的月份,它将影响月份和年份。如果一天大于当月的天数,它也会影响月份。没有什么会影响年份(除非您通过的年份少于 100,在这种情况下,它被视为 1900 + 年(。

你可以尝试这样的事情:

根据规格的说明:

当我们调用具有 2 个或更多参数的日期构造函数时,它会尝试使用以下构造函数 ref 进行处理:

new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )

在这里,如果有任何值没有被传递,它将被设置为NaN,稍后将被解析为+0。因此时间戳是0:0:0

现在的诀窍在于一个内部称为的函数:MakeDay。

如您所见,第 8 点,它返回

Day(t) + dt − 1

在这里Day(t)将返回毫秒数,日期将根据dt - 1计算。由于我们正在传递0,日期值将是-1 + milliseconds,因此它返回前一天。

另一种方法是为下个月的 1 日创建日期,并将1减去为 daysec 。您可以根据需要选择任何人,

function isValidDate(year, month, day) {
  var d = new Date(year, month, day);
  return !!(d.getFullYear() == year && d.getMonth() == month && d.getDate() == day)
}
function computeLastPossibleDate(y,m,d){
  return new Date(y, m+1, 0);
}
function test(y,m,d){
  return isValidDate(y,m,d) ? new Date(y,m,d) : computeLastPossibleDate(y,m,d)
}
// 31st Feb.
console.log(test(2017, 1, 31).toString())
// 31st March
console.log(test(2017, 2, 31).toString())
// 31st April
console.log(test(2017, 3, 31).toString())
// 50th Dec.
console.log(test(2017, 11, 50).toString())

注意:如果缺少任何内容,请将其作为评论与您的投票分享。只是投票而不加评论对任何人都没有帮助。

function isValidDate(year, month, day) {
    var d = new Date(year, month, day);
    if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
        return d;
    }
    else
        rturn new Date(year, month, 0);;
}
  function isValidDate(year, month, day) {
    if(month<=12){
        var temp_day=day;
        var d = new Date(year, month, day);
        var lastDay = new Date(d.getFullYear(), d.getMonth(),0);
        var getlastday=lastDay.getDate();
        if(getlastday<=day){
            //var date=(d.getDate())+"/"+(d.getMonth())+"/"+(d.getFullYear());
            var date=(getlastday)+"-"+(month)+"-"+(lastDay.getFullYear());
            return date;
        }else{
            //var date=(lastDay.getDate())+"-"+(lastDay.getMonth())+"-"+(lastDay.getFullYear());
            var date=(day)+"/"+(month)+"/"+(year);
            return date;
        }
    }
    else{
        return "month not valid";
    }
}

试试这个代码

最新更新