How to create an array of days starting with today and going back the last 30 days in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "time"
)

func main() {
    // Get today's date
    today := time.Now()

    // Create a slice to hold the days
    days := make([]time.Time, 30)

    // Populate the slice with dates from today going back 30 days
    for i := 0; i < 30; i++ {
        days[i] = today.AddDate(0, 0, -i)
    }

    for _, day := range days {
        fmt.Println(day.Format("02")) // Extract and print only the day of the month
    }
}



/*
run:

11
10
09
08
07
06
05
04
03
02
01
31
30
29
28
27
26
25
24
23
22
21
20
19
18
17
16
15
14
13

*/

 



answered Apr 11, 2025 by avibootz
...