Check if year is leap year in javascript [duplicat

2019-01-03 16:43发布

This question already has an answer here:

 function leapYear(year){
    var result; 
    year = parseInt(document.getElementById("isYear").value);
    if (years/400){
      result = true
    }
    else if(years/100){
      result = false
    }
    else if(years/4){
      result= true
    }
    else{
      result= false
    }
    return result
 }

This is what I have so far (the entry is on a from thus stored in "isYear"), I basically followed this here, so using what I already have, how can I check if the entry is a leap year based on these conditions(note I may have done it wrong when implementing the pseudocode, please correct me if I have) Edit: Note this needs to use an integer not a date function

7条回答
唯我独甜
2楼-- · 2019-01-03 16:58

The function checks if February has 29 days. If it does, then we have a leap year.

function isLeap(year) {
  return new Date(year, 1, 29).getDate() === 29;
}

ES6

let isLeap = (year) => new Date(year, 1, 29).getDate() === 29;

isLeap(1004) // true
isLeap(1001) // false
查看更多
乱世女痞
3楼-- · 2019-01-03 17:01

If you're doing this in an Node.js app, you can use the leap-year package:

npm install --save leap-year

Then from your app, use the following code to verify whether the provided year or date object is a leap year:

var leapYear = require('leap-year');

leapYear(2014);
//=> false 

leapYear(2016);
//=> true 

Using a library like this has the advantage that you don't have to deal with the dirty details of getting all of the special cases right, since the library takes care of that.

查看更多
ら.Afraid
4楼-- · 2019-01-03 17:08

A faster solution is provided by Kevin P. Rice here:https://stackoverflow.com/a/11595914/5535820 So here's the code:

function leapYear(year)
{
    return (year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0);
}
查看更多
做自己的国王
5楼-- · 2019-01-03 17:09

You can try using JavaScript's Date Object

new Date(year,month).getFullYear()%4==0

This will return true or false.

查看更多
Juvenile、少年°
6楼-- · 2019-01-03 17:12
function leapYear(year)
{
  return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
查看更多
狗以群分
7楼-- · 2019-01-03 17:17

My Code Is Very Easy To Understand

var year = 2015;
var LeapYear = year % 4;

if (LeapYear==0) {
    alert("This is Leap Year");
} else {
    alert("This is not leap year");
}
查看更多
登录 后发表回答