Check if year is leap year in javascript [duplicate]

早过忘川 提交于 2019-11-26 03:57:14

问题


 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


回答1:


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



回答2:


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

ES5

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

ES6

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

Result

isLeap(1004) // true
isLeap(1001) // false



回答3:


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);
}



回答4:


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.




回答5:


You can use the following code to check if it's a leap year:

ily = function(yr) {
    return (yr % 400) ? ((yr % 100) ? ((yr % 4) ? false : true) : false) : true;
}



回答6:


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");
}



回答7:


You can try using JavaScript's Date Object

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

This will return true or false.



来源:https://stackoverflow.com/questions/16353211/check-if-year-is-leap-year-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!