JavaScript验证日期并返回日历的最后可用日期 [英] JavaScript validate date and return last available date of calendar

查看:65
本文介绍了JavaScript验证日期并返回日历的最后可用日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to validate my date if date not exits in calendar then return me last available date of calendar,

示例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



<这是我首先尝试使用以下函数验证日期,我如何为abov制作逻辑e日期。

This is i am first trying to validate date using below function,how i can make logic for above dates.

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


推荐答案

你可以尝试这样的事情:

You can try something like this:

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

When we call date constructor with 2 or more arguments, it tries to process using following constructor ref:

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

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

Here if any value that is not passed, it will be set as NaN and later will be parsed to +0. Hence timestamp is 0:0:0

现在诀窍在于一个内部调用的函数: MakeDay

Now the trick is in a function called internally: MakeDay.

如第8点所示,它返回

Day(t) + dt − 1

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

Here Day(t) would return number of milliseconds and date would be calculated based on dt - 1. Since we are passing 0, date value would be -1 + milliseconds and hence it returns previous day.

另一个替代方案是创建下个月1日的日期,并将 1 减去 sec 。您可以根据需要选择任何人,

Another alternate would be to create date for 1st of next month and subtract 1 as day or sec. You can select anyone based on the need,

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

注意:如果如有任何遗漏,请在投票时将其作为评论分享。只是投票而不发表评论对任何人都没有帮助。

Note: If there is anything missing, please share it as a comment with your vote. Just vote without comment will not help anyone.

这篇关于JavaScript验证日期并返回日历的最后可用日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆