How to validate date taking into account leap year? [closed]
closed. this question is out of scope and is not currently accepting answers.
want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 5 months ago .
improve this questionHow to validate date with Leap Year in JavaScript?
12
Author: bfavaretto, 2014-06-18
5 answers
Another way is to check which month falls on February 29 (February 29 or March 1?). If it is February the year is LEAP:
function anoBissexto(ano) {
return new Date(ano, 1, 29).getMonth() == 1
}
Remembering that the months range from 0 to 11 for the JavaScript Date object (month 1 is February).
13
Author: talles, 2014-06-18 12:40:10
Hello, try this here:
function leapYear(year){
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
4
Author: f.fujihara, 2014-06-18 12:15:46
Date validation with javascript, also checks if the year is Leap Year.
<html>
<head>
<title>valida data</title>
<script>
function valData(data){//dd/mm/aaaa
day = data.substring(0,2);
month = data.substring(3,5);
year = data.substring(6,10);
if( (month==01) || (month==03) || (month==05) || (month==07) || (month==08) || (month==10) || (month==12) ) {//mes com 31 dias
if( (day < 01) || (day > 31) ){
alert('invalid date');
}
} else
if( (month==04) || (month==06) || (month==09) || (month==11) ){//mes com 30 dias
if( (day < 01) || (day > 30) ){
alert('invalid date');
}
} else
if( (month==02) ){//February and leap year
if( (year % 4 == 0) && ( (year % 100 != 0) || (year % 400 == 0) ) ){
if( (day < 01) || (day > 29) ){
alert('invalid date');
}
} else {
if( (day < 01) || (day > 28) ){
alert('invalid date');
}
}
}
}
</script>
</head>
<body>
<form>
<input type="text" name="data" id="data" onBlur="return valData(this.value)" />
</form>
</body>
</html>
4
Author: Flaviano Silva, 2014-06-18 12:31:09
Here is a function I did. It's simple and works in a way:
function ValidarData() {
var aAr = typeof (arguments[0]) == "string" ? arguments[0].split("/") : arguments,
lDay = parseInt(aAr[0]), lMon = parseInt(aAr[1]), lYear = parseInt(aAr[2]),
BiY = (lYear % 4 == 0 && lYear % 100 != 0) || lYear % 400 == 0,
MT = [1, BiY ? -1 : -2, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1];
return lMon <= 12 && lMon > 0 && lDay <= MT[lMon - 1] + 30 && lDay > 0;
}
ValidarData(31,12,2016) // True
Or
ValidarData("29/02/2017") // False
-1
Author: Lucas Martins, 2016-03-27 07:58:52
if ((ano % 4 == 0) && ((ano % 100 != 0) || (ano % 400 == 0))
-3
Author: stromdh, 2020-03-13 20:10:58