Created
October 5, 2023 19:13
-
-
Save atombrella/44f6538f66cd990ea2e56ee55f70dd8d to your computer and use it in GitHub Desktop.
Find second last Wednesday of the Month
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package utils | |
import "time" | |
func SecondLastWednesday(year int, month time.Month) int { | |
t := time.Date(year, month, 1, 0, 0, 0, 0, time.Local) | |
lastOfMonth := t.AddDate(0, 1, -1) | |
if lastOfMonth.Weekday() == 3 { | |
// Last day is a Wednesday | |
return (lastOfMonth.Day() - 7) | |
} else if lastOfMonth.Weekday() > 3 { | |
// Later than a Wednesday | |
return lastOfMonth.Day() - (int(lastOfMonth.Weekday()) - 3) - 7 | |
} else { | |
// Earlier than a Wednesday. Find what would've been the next | |
return (lastOfMonth.Day() + (3 - int(lastOfMonth.Weekday()))) - 14 | |
} | |
} | |
// test | |
package utils | |
import ( | |
"testing" | |
"time" | |
) | |
type wednesdayTest struct { | |
year int | |
month time.Month | |
expected int | |
} | |
var addTests = []wednesdayTest{ | |
{2021, time.September, 22}, // Last day a Thursday | |
{2020, time.October, 21}, // Last day a Saturday | |
{2020, time.March, 18}, // Last day is a Tueday | |
{2023, time.May, 24}, // Last day a Wednesday | |
} | |
func TestSecondLastWednesday(t *testing.T) { | |
for _, test := range addTests { | |
if output := SecondLastWednesday(test.year, test.month); output != test.expected { | |
t.Errorf("Output %d not equal to expected %d", output, test.expected) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment