Visit the leap exercise on Exercism to read the full instructions and download the exercise files.
Dig Deeper
Boolean chain
Using Boolean chain
function Test-Leap([int] $year) {
$year % 4 -eq 0 -and $year % 100 -ne 0 -or $year % 400 -eq 0
}
One of the most common approach to solve this exercise based on the given information.
First we test if the year is divisible by 4 using modulus, if it return false here then the chain is short circuit and return false.
If the year is indeed divisible by 4, then we test whether it can’t divisible by 100 or can divisible by 400.
If one of those condition return true then our chain will return true, but if both return false then our chain here will return false.
You can visualize the chain like this:
| divisible by 4 | not divisible by 100 | divisible by 400 | |
|---|
| false (short circuit) | | | => false |
| true | either this is true | or this to be true | => true |
| true | false | false | => false |
Arithmetic operators
datetime object
Using DateTime object
function Test-Leap([int] $year) {
(Get-Date -Year $year -Month 2 -Day 29).Month -eq 2
}
The main characteristic of a leap year is the second month (February) has 29 days instead of 28.
In this approach we will use Get-Date with : $year for Year parameter, 2 for Month Parameter, and 29 for Day parameter, and this will give us a DateTime object.
Next we access the Month property of this object and compare it with 2, if they are equal then the year is a leap year.
In the event of a year is not a leap year, Get-Date for Month 2 and Day 29 in fact return a DateTime object of March the 1st, which mean the Month property now has the value of 3.
Get-Date cmdlet.
built-in method
Using IsLeapYear method
function Test-Leap([int] $year) {
[DateTime]::IsLeapYear($year)
}
Utilizing the DateTime class from .NET, you can determine if a year is a leap year or not by passing it into the IsLeapYear static method.
This might not be the intended approach for learning, but it is an idiomatic way to check if a year is leap or not.
IsLeapYear method.
Source: Exercism powershell/leap