We usually verify the date in JavaScript, the basic idea is to determine whether the day is valid, and then judge whether the month has the day, such as some months without 31st, excepting Hile No 29, 30th, Leap year February without 30th and so on.
Accidentally found a skill to judge all the above. Drop assignment code, the actual code is only two lines.
In fact, this technique is also very simple, by instantiating the date object to generate a valid day, and then comparing the date and date is equal to verify that the dates are legitimate.
var originalyear = 2016;
var originalmonth =;
var originalday =;
var date = new Date (Originalyear, originalMonth-1, originalday);
var year = Date.getfullyear ();
var month = Date.getmonth () + 1;
var day = Date.getdate ();
Console.log (year + '-' + month + '-' + Day '); 2017-1-1
Because December is not 32 days, so the date is the second year of January 1, the month and the day is not equal, so 32 days is not a legal date.
The specific implementation code:
var validatedate = function (Originalyear, Originalmonth, originalday) {
var date = new Date (Originalyear, Originalmon Th-1, originalday);
var year = Date.getfullyear ();
var month = Date.getmonth () + 1;
var day = Date.getdate ();
Return year = = Originalyear && month = = Originalmonth && Day = = Originalday;
}
Test:
Console.log (Validatedate ()); False
Console.log (Validatedate ( -1,-1,-1));//False
Console.log (validatedate (', ', ', '));//False
Console.log (Validatedate ([], [], [])); False
Console.log (Validatedate ({}, {}, {}));//False
//excepting February.
Console.log (Validatedate (2015, 2));//False
/Leap year February.
Console.log (Validatedate (2016, 2));/True
Console.log (Validatedate (2016, 6,);//True
Console.log (Validatedate (2016, 6, 31)); False
Console.log (validatedate (' 2016 ', ', ', '));//True
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.