How to find the dates of the last Fridays of each month of a given year in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "os"
    "strconv"
    "time"
)

// Return all last Fridays of each month in a given year
func LastFridaysOfYear(year int) []time.Time {
    results := make([]time.Time, 0, 12)

    for month := 1; month <= 12; month++ {

        // Last day of the month
        date := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC).
            AddDate(0, 1, 0). // AddMonths(1)
            AddDate(0, 0, -1) // AddDays(-1)

        // Walk backward to Friday
        for date.Weekday() != time.Friday {
            date = date.AddDate(0, 0, -1)
        }

        results = append(results, date)
    }

    return results
}

func main() {
    year := 2026

    if len(os.Args) > 1 {
        if y, err := strconv.Atoi(os.Args[1]); err == nil {
            year = y
        }
    }

    for _, date := range LastFridaysOfYear(year) {
        fmt.Println(date.Format("01/02/2006"))
    }
}



/*
run:

01/30/2026
02/27/2026
03/27/2026
04/24/2026
05/29/2026
06/26/2026
07/31/2026
08/28/2026
09/25/2026
10/30/2026
11/27/2026
12/25/2026

*/

 



answered May 23 by avibootz

Related questions

...