Sep 19 2019 09:43 AM
Over the years I've run into several situations where we've needed to determine if the year is a leap year; most recently to determine the number of working days to calculate billable time - not the important part. I remember being taught as a kid the easy way to figure it out in your head but couldn't find a simple way to do in an Excel formula/cell.
Figure out in your head: I'm realizing a lot of the tricks I was shown as a kid may not be making it into the school system or are just lost arts of thinking...so I will share and hopefully you will learn something new as well.
Looking at positions 3 and 4 of the year is all you need to determine the leap year.
Is position 3 odd or even? (in 2019 this is the "1")
Odd: then only the last position of "2" or "6" are a leap year. So 2012 and 2016 were leap years.
Even: then the last positions of "0", "4" or "8" are leap years. So 2002, 2004, 2008 were all leap years.
Feel free to check me on any year....1944 - yep a leap year. 1972 - also a leap year. Knock yourself out.
Excel formula
So even with this knowledge it is not easy to turn this into usable information in Excel...until this formula. It is applying the same logic above, into a single field formula.
When you put it all together this is what it looks like.
=IF(MOD(MID(YEAR($A3),3,1),2)=0,IF(MOD(MID(YEAR($A3),4,1),4)=0,"Leap","No"),IF(OR(MID(YEAR($A3),4,1)="2",MID(YEAR($A3),4,1)="6"),"Leap","No"))
It can be a little confusing so let's break it down. Here is the pseudo syntax to help it all make sense:
Now that wasn't too hard...but it can be difficult and get lost in the formula.
So breaking down the formula to align with this pseudo code can help. We have to explain some of the values in our formula - so let's start with the assumption that
If the 3 position of the year is evenly divisible by 2 then A (even), else B (odd).
=IF(MOD(MID(YEAR($A3),3,1),2)=0, {EVEN},{ODD})
Now the sub if statements
A (even): If the 4th/last position of the year is evenly divisible by 4 then it is a leap year, if not it isn't a leap year.
IF(MOD(MID(YEAR($A3),4,1),4)=0,"Leap","No"
B (odd): If the last position of the year is either a 2 or a 6 then it is a leap year, if not it isn't a leap year.
IF(OR(MID(YEAR($A3),4,1)="2",MID(YEAR($A3),4,1)="6"),"Leap","No"
When you put it all together this is what it looks like.
=IF(MOD(MID(YEAR($A3),3,1),2)=0,IF(MOD(MID(YEAR($A3),4,1),4)=0,"Leap","No"),IF(OR(MID(YEAR($A3),4,1)="2",MID(YEAR($A3),4,1)="6"),"Leap","No"))
I hope this helps or gives you ideas for other problems you can solve.
Sep 19 2019 10:01 AM
Sep 19 2019 11:04 AM
Sep 19 2019 12:38 PM
@Sergei Baklan Well...if you want to do it the easy way I guess you could do that...doesn't have as good of a story. :)
Sep 19 2019 01:01 PM
Story is great, but in coding I prefer to keep things simple