How to validate date taking into account leap year?

Asked

Viewed 14,658 times

12

How to validate leap year date in Javascript?

5 answers

14

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 go from 0 to 11 for the Javascript Date object (the month 1 is February).

  • 1

    I like it, good logic.

4

Hey, try this here:

function leapYear(year){
    return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}

4

date validation with javascript, also checks whether the year is leap.

<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>
  • 1

    I find a lot of code for little result, when your code is too extensive for very little means it wasn’t developed properly. Someone once told me Um código perfeito não é aquele que não se tem mais nada para colocar nele, mas sim o código em que você não tem mais nada para tirar dele.

  • That was missing look: if( (month >12)){ alert('invalid date'); } is entering month above 12.

-2

Here’s a function I did. It’s simple and it 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

-4

if ((ano % 4 == 0) && ((ano % 100 != 0) || (ano % 400 == 0))
  • Stromdh, explain what the code, which you answered, does.

  • How different is your answer from that of f.fujihara?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.