How to determine whether a year is a leap year in JavaScript - javascript

I'm trying to determine whether a year is a leap year or not. I'm not sure where i'm missing something because this code is meant to determine that.
Thanks for your help.
let Year = (year) => {
this.year = year;
};
Year.prototype.isLeap = () => {
return (
this.year % 400 === 0 ||
(this.year % 4 === 0 && (this.year % 100 === 0))
);
};
let year = new Year(2014);
year.isLeap();
Thanks I've figured it out.
Initially i did it will the kind of If statement you guys are pointing to here!, so I'm now refactoring to av a cleaner code.
My code was having issue on this line
(this.year % 4 === 0 && (this.year % 100 === 0))
the right syntax is
(this.year % 4 === 0 && !(this.year % 100 === 0))

You could just check the feburary 29th of the given year and see if its changes to march 1st.
const date = new Date(this.year, 1, 29);
return date.getMonth() === 1;
If getMonth() returns 1, then its still feburary which means its leap year.

Number.prototype.isLeap = function() {
return !(this % 4 || !(this % 100) && this % 400);
}
let year = 2000;
console.log(year.isLeap()); // prints true
year = 1900;
console.log(year.isLeap()); // prints false
year = 1904;
console.log(year.isLeap()); // prints true
year = 2003;
console.log(year.isLeap()); // prints false

The following code block will work well on Javascript and also on Typescript if you remove the function keyword. To understand the logic behind this implementation have a look at this link How to determine whether a year is a leap year.
function isLeapYear(year) {
let isLeapObj = {};
if ((year % 4 === 0 && year % 100 != 0) || year % 400 === 0) {
isLeapObj['isLeap'] = true;
isLeapObj['days'] = 366;
} else {
isLeapObj['isLeap'] = false;
isLeapObj['days'] = 365;
}
return isLeapObj;
}
x = isLeapYear(2020);
console.log(x);
For Javscript use the following code

In regards to #brenjt's answer above you might want to change the value 29 to 30
const date = new Date(this.year, 1, 30);
if (date.getMonth() === 1) {
console.log("it's not a leap year");
} else {
console.log("it's a leap year");
}

Related

Function is not repeating all if statement

Hi I have a Problem my code is just executing ones but the loop works if i want to console log i
the only thing whats is logged normaly to the console is:
377 2 2021
(here is the code):
let time = (Math.floor(target / aDM));
let tDay = currentDate[0] + time
let tMonth = currentDate[1]
let tYear = currentDate[2]
targetDate()
function targetDate() {
let i = 0
while (i < 100) {
if (tMonth % 2 === 1 && tMonth && tDay > 30) {
tMonth++;
tDay = (tDay - 30);
}
if (tYear % 2 === 0 && tMonth != 2 && tDay > 30) {
tMonth++;
tDay = (tDay - 30);
}
if (tMonth % 2 === 1 && tMonth != 2 && tDay > 31) {
tMonth++;
tDay = (tDay - 31)
}
if (tMonth > 28) {
tDay++;
tDay = (tDay - 31)
}
if (tMonth > 12) {
tMonth = (tMonth - 12)
tYear++
}
i++;
}
console.log(tDay, tMonth, tYear)
}
you have several problems with this code.
Not good practice to use global variables. you should pass your variables into the function.
You probably want "else"s in your code. otherwise its possible for the code to execute several of those conditions at once for the same iteration of i.
Your logic: (tMonth % 2 === 1) is flawed because if you start with tMonth % 2 == 0, there's no way for it to get to 1
All of this logic seems overly complicated and likely to fail. Far simpler to use standard date functions if you are simply trying to step through days of a year.
What about leap years?
Months do not simply alternate from 30 to 31 and back. in fact right in the middle of the year (July & august) you have back to back 31 day months.

Check if Saturday and Sunday exist between two days in Javascript [duplicate]

Wondering if anyone has a solution for checking if a weekend exist between two dates and its range.
var date1 = 'Apr 10, 2014';
var date2 = 'Apr 14, 2014';
funck isWeekend(date1,date2){
//do function
return isWeekend;
}
Thank you in advance.
EDIT Adding what I've got so far. Check the two days.
function isWeekend(date1,date2){
//do function
if(date1.getDay() == 6 || date1.getDay() == 0){
return isWeekend;
console.log("weekend")
}
if(date2.getDay() == 6 || date2.getDay() == 0){
return isWeekend;
console.log("weekend")
}
}
Easiest would be to just iterate over the dates and return if any of the days are 6 (Saturday) or 0 (Sunday)
Demo: http://jsfiddle.net/abhitalks/xtD5V/1/
Code:
function isWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2),
isWeekend = false;
while (d1 < d2) {
var day = d1.getDay();
isWeekend = (day === 6) || (day === 0);
if (isWeekend) { return true; } // return immediately if weekend found
d1.setDate(d1.getDate() + 1);
}
return false;
}
If you want to check if the whole weekend exists between the two dates, then change the code slightly:
Demo 2: http://jsfiddle.net/abhitalks/xtD5V/2/
Code:
function isFullWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2);
while (d1 < d2) {
var day = d1.getDay();
if ((day === 6) || (day === 0)) {
var nextDate = d1; // if one weekend is found, check the next date
nextDate.setDate(d1.getDate() + 1); // set the next date
var nextDay = nextDate.getDay(); // get the next day
if ((nextDay === 6) || (nextDay === 0)) {
return true; // if next day is also a weekend, return true
}
}
d1.setDate(d1.getDate() + 1);
}
return false;
}
You are only checking if the first or second date is a weekend day.
Loop from the first to the second date, returning true only if one of the days in between falls on a weekend-day:
function isWeekend(date1,date2){
var date1 = new Date(date1), date2 = new Date(date2);
//Your second code snippet implies that you are passing date objects
//to the function, which differs from the first. If it's the second,
//just miss out creating new date objects.
while(date1 < date2){
var dayNo = date1.getDay();
date1.setDate(date1.getDate()+1)
if(!dayNo || dayNo == 6){
return true;
}
}
}
JSFiddle
Here's what I'd suggest to test if a weekend day falls within the range of two dates (which I think is what you were asking):
function containsWeekend(d1, d2)
{
// note: I'm assuming d2 is later than d1 and that both d1 and d2 are actually dates
// you might want to add code to check those conditions
var interval = (d2 - d1) / (1000 * 60 * 60 * 24); // convert to days
if (interval > 5) {
return true; // must contain a weekend day
}
var day1 = d1.getDay();
var day2 = d2.getDay();
return !(day1 > 0 && day2 < 6 && day2 > day1);
}
fiddle
If you need to check if a whole weekend exists within the range, then it's only slightly more complicated.
It doesn't really make sense to pass in two dates, especially when they are 4 days apart. Here is one that only uses one day which makes much more sense IMHO:
var date1 = 'Apr 10, 2014';
function isWeekend(date1){
var aDate1 = new Date(date1);
var dayOfWeek = aDate1.getDay();
return ((dayOfWeek == 0) || (dayOfWeek == 6));
}
I guess this is the one what #MattBurland sugested for doing it without a loop
function isWeekend(start,end){
start = new Date(start);
if (start.getDay() == 0 || start.getDay() == 6) return true;
end = new Date(end);
var day_diff = (end - start) / (1000 * 60 * 60 * 24);
var end_day = start.getDay() + day_diff;
if (end_day > 5) return true;
return false;
}
FIDDLE
Whithout loops, considering "sunday" first day of week (0):
Check the first date day of week, if is weekend day return true.
SUM "day of the week" of the first day of the range and the number of days in the lap.
If sum>5 return true
Use Date.getDay() to tell if it is a weekend.
if(tempDate.getDay()==6 || tempDate.getDay()==0)
Check this working sample:
http://jsfiddle.net/danyu/EKP6H/2/
This will list out all weekends in date span.
Modify it to adapt to requirements.
Good luck.

Check if year is leap year in javascript [duplicate]

This question already has answers here:
javascript to find leap year
(15 answers)
Closed 4 years ago.
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
function leapYear(year)
{
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
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
const isLeap = year => new Date(year, 1, 29).getDate() === 29;
Result
isLeap(1004) // true
isLeap(1001) // false
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);
}
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.
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;
}
You can try using JavaScript's Date Object
new Date(year,month).getFullYear()%4==0
This will return true or false.
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");
}

How do I display all the leap years between two year in javascript

How do I create an HTML page which accepts user input into the text field as integer between 1900 and 2012. When the user presses the “Display” button, the function created in JavaScript should able to display all the leap year between the inputted integer and 2012.
example:
When user enters in "1970" in the text field then the result is:
1972
1976
1980
1984
1988
1992
1996
2000
2004
2008
I have code like this
var str = '';
var i;
for ( i = 1970; i < 2012; i += 1 ) {
if ( new Date( i, 1, 29 ).getMonth() === 1 ) {
str += '<p>' + i + '</p>';
}
}
document.body.innerHTML = str;
I don't understand how to tie this function to the button?
​
I assume that you want to calculate what years a leap years in the Gregorian Calendar, introduced 1582. In the Gregorian calendar there are 97 leap years in 400 years.
Every year that is evenly divisible by 4, but not 100, but 400 is a leap year. 1600 and 2000 is, but not 1700, 1800, 1900.
Here is a solution that takes into account all the rules for leap years in the Gregorian calendar:
for (var i=1890; i < 2010; ++i) {
if (!(i%4)&&(i%100)||!(i%400) ) console.log(i);
}
The rule can also be written as
( ( (year % 4) == 0) && ( (year % 100) !== 0)) || ( (year % 400) ==0)
To be able to bind this to a button you must put it inside a function:
function printLeapYears() {
//Do your thing here
}
Then you must bind it to your button. For example
<button type="button" onclick="printLeapYears()">print leap years</button>
There are other ways to bind the function to the button. Since this is a homework question and I don't know if you are familiar with ids and document.getElementById yet, this solution will probably be enough.
Just for fun, here's an approach that just tests years divisible by four:
function getLeapYears(start, end) {
var startYear = Math.ceil(start / 4) * 4;
var endYear = Math.floor(end / 4) * 4;
var leapYears = [];
if (isNaN(startYear) || isNaN(endYear)) return ['Invalid input'];
while (startYear <= endYear) {
if ( startYear % 100 || !(startYear % 400)) {
leapYears.push(startYear);
}
startYear += 4;
}
return leapYears.length? leapYears : ['None'];
}
And here's one way (some might say not "best practice") to put it in a page:
Start year: <input id="i0"><br>
End year: <input id="i1"><br>
<button onclick="
var start = document.getElementById('i0');
var end = document.getElementById('i1');
var el = document.getElementById('s0');
if (start && end && el) {
el.innerHTML = getLeapYears(start.value, end.value).join('<br>');
}
">List leapyears</button><br>
<span id="s0"></span>

javascript to find leap year

How can I get the code below to work when I have a month of february? Currently it is getting to the day and then stopping before getting to the if to determine whether it is a leap year.
if (month == 2) {
if (day == 29) {
if (year % 4 != 0 || year % 100 == 0 && year % 400 != 0) {
field.focus();
field.value = month +'/' + '';
}
}
else if (day > 28) {
field.focus();
field.value = month +'/' + '';
}
}
It's safer to use Date objects for datetime stuff, e.g.
isLeap = new Date(year, 1, 29).getMonth() == 1
Since people keep asking about how exactly this works, it has to do with how JS calculates the date value from year-month-day (details here). Basically, it first calculates the first of the month and then adds N -1 days to it. So when we're asking for the 29th Feb on a non-leap year, the result will be the 1st Feb + 28 days = 1st March:
> new Date(2015, 1, 29)
< Sun Mar 01 2015 00:00:00 GMT+0100 (CET)
On a leap year, the 1st + 28 = 29th Feb:
> new Date(2016, 1, 29)
< Mon Feb 29 2016 00:00:00 GMT+0100 (CET)
In the code above, I set the date to 29th Feb and look if a roll-over took place. If not (the month is still 1, i.e. February), this is a leap year, otherwise a non-leap one.
Compared to using new Date() this is is around 100 times faster!
Update:
This latest version uses a bit test of the bottom 3 bits (is it a multiple of 4), as well as a check for the year being a multiple of 16 (bottom 4 bits in binary is 15) and being a multiple of 25.
ily = function(y) {return !(y & 3 || !(y % 25) && y & 15);};
http://jsperf.com/ily/15
It is slightly faster again than my previous version (below):
ily = function(yr) {return !((yr % 4) || (!(yr % 100) && (yr % 400)));};
http://jsperf.com/ily/7
It is also 5% faster, compared to the already fast conditional operator version by broc.seib
Speed Test results: http://jsperf.com/ily/6
Expected logic test results:
alert(ily(1900)); // false
alert(ily(2000)); // true
alert(ily(2001)); // false
alert(ily(2002)); // false
alert(ily(2003)); // false
alert(ily(2004)); // true
alert(ily(2100)); // false
alert(ily(2400)); // true
isLeap = !(new Date(year, 1, 29).getMonth()-1)
...subtraction by one should work even faster than compare on most CPU architectures.
Correct and Fast:
ily = function(yr) { return (yr%400)?((yr%100)?((yr%4)?false:true):false):true; }
If you are in a loop or counting the nanoseconds, this is two magnitudes faster than running your year through a new Date() object. Compare the performance here: http://jsperf.com/ily
Better historical computation of leap years.
The code below takes into account that leap years were introduced in 45BC with the Julian calendar, and that the majority of the Western world adopted the Gregorian calendar in 1582CE, and that 0CE = 1BC.
isLeap = function(yr) {
if (yr > 1582) return !((yr % 4) || (!(yr % 100) && (yr % 400)));
if (yr >= 0) return !(yr % 4);
if (yr >= -45) return !((yr + 1) % 4);
return false;
};
Britain and its colonies adopted the Gregorian calendar in 1752, so if you are more Anglo centric this version is better (We'll assume Britain adopted the Julian calendar with Roman conquest starting in 43CE).
isLeap = function(yr) {
if (yr > 1752) return !((yr % 4) || (!(yr % 100) && (yr % 400)));
if (yr >= 43) return !(yr % 4);
return false;
};
JavaScript is expected to be getting a new Date/Time API which exposes a new global object - Temporal. This global object provides JS devs with a nicer way to deal with dates/times. It is currently a stage 3 proposal and should hopefully be available for use shortly.
The temporal api exposes a nice property for checking for leap years - inLeapYear. This returns true if a particular date is a leap year, otherwise false. Below we're using with() to convert the date returned by plainDateISO to one with our particular year:
const isLeap = year => Temporal.now.plainDateISO().with({year}).inLeapYear;
console.log(isLeap(2020)); // true
console.log(isLeap(2000)); // true
console.log(isLeap(1944)); // true
console.log(isLeap(2021)); // false
console.log(isLeap(1999)); // false
If you just want to check if your current system date time is a leap year, you can omit the .with():
// true if this year is a leap year, false if it's not a leap year
const isLeap = Temporal.now.plainDateISO().inLeapYear;
I use this because I hate having to keep referring to January as 0 and February as 1.
To me and PHP and readable dates, February=2. I know it doesn't really matter as the number never changes but it just keeps my brain thinking the same across different code.
var year = 2012;
var isLeap = new Date(year,2,1,-1).getDate()==29;
You can easily make this to work calling .isLeapYear() from momentjs:
var notLeapYear = moment('2018-02-29')
console.log(notLeapYear.isLeapYear()); // false
var leapYear = moment('2020-02-29')
console.log(leapYear.isLeapYear()); // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
all in one line 😉
const isLeapYear = (year) => (year % 100 === 0 ? year % 400 === 0 : year % 4 === 0);
console.log(isLeapYear(2016)); // true
console.log(isLeapYear(2000)); // true
console.log(isLeapYear(1700)); // false
console.log(isLeapYear(1800)); // false
console.log(isLeapYear(2020)); // true
function isLeap(year) {
if ( (year % 4 === 0 && year % 100 !== 0) || (year % 4 === 0 && year % 100 === 0 && year % 400 === 0) ) {
return 'Leap year.'
} else {
return 'Not leap year.';
}
}
Pseudo code
if year is not divisible by 4 then not leap year
else if year is not divisible by 100 then leap year
else if year is divisible by 400 then leap year
else not leap year
JavaScript
function isLeapYear (year) {
return year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 )
}
Using the above code insures you do only one check per year if the year is not divisible by 4
Just by adding the brackets you save 2 checks per year that is not divisible by 4
Another alternative is to see if that year has the date of February 29th. If it does have this date, then you know it is a leap year.
ES6
// Months are zero-based integers between 0 and 11, where Febuary = 1
const isLeapYear = year => new Date(year, 1, 29).getDate() === 29;
Tests
> isLeapYear(2016);
< true
> isLeapYear(2019);
< false
function leapYear(year){
if((year%4==0) && (year%100 !==0) || (year%400==0)){
return true;
}
else{
return false;
}
}
var result = leapYear(1700);
console.log(result);
Alternative non-conditionals solution:
const leapYear = y => (y % 4 === 0) + (y % 100 !== 0) + (y % 400 === 0) === 2
Use this:
Date.prototype.isLeap = function() {
return new Date(this.getFullYear(), 1, 29).getMonth() == 1;
};
Date.prototype.isLeap = function() {
return new Date(this.getFullYear(), 1, 29).getMonth() == 1;
};
console.log(new Date("10 Jan 2020").isLeap()); // True
console.log(new Date("10 Jan 2022").isLeap()); // False

Categories