How to create a list of random dates in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math/rand"
    "time"
)

// Generate a random date between two years using time.Time
func randomDate(startYear, endYear int) time.Time {

    // Convert start and end years to timestamps
    start := time.Date(startYear, time.January, 1, 0, 0, 0, 0, time.UTC)
    end   := time.Date(endYear, time.December, 31, 0, 0, 0, 0, time.UTC)

    startUnix := start.Unix()
    endUnix   := end.Unix()

    // Uniform distribution over the timestamp range
    randomUnix := rand.Int63n(endUnix-startUnix+1) + startUnix

    // Convert back to time.Time
    return time.Unix(randomUnix, 0)
}

func main() {
    rand.Seed(time.Now().UnixNano()) // Seed RNG

    dates := make([]time.Time, 0, 10)

    for i := 0; i < 10; i++ {
        dates = append(dates, randomDate(1990, 2030))
    }

    for _, d := range dates {
        fmt.Printf("%d-%d-%d\n", d.Year(), d.Month(), d.Day())
    }
}



/*
run:

2021-1-2
2006-2-11
2015-5-2
1995-1-2
1997-4-14
2015-3-27
1997-9-12
2013-5-4
2026-7-26
1994-5-10

*/

 



answered 3 hours ago by avibootz
...