JavaScript validate date and return last available date of calendar

前端 未结 4 853
栀梦
栀梦 2021-01-27 03:19

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

Example 01

Input Date    : 31         


        
4条回答
  •  Happy的楠姐
    2021-01-27 04:03

    You can try something like this:

    Explanation as per spec:

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

    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

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

    As you see point 8, it returns

    Day(t) + dt − 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.

    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.

提交回复
热议问题