In this article, we will see how to generate a random date between two dates in golang.

In golang, we can use Date function in the time package to generate a random date between two dates.

Following is the example of how to generate random date between two dates in golang

package main

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

func main() {
    startDate := time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC)
    endDate := time.Date(2022, 12, 31, 0, 0, 0, 0, time.UTC)

    duration := endDate.Sub(startDate)
    randomDuration := time.Duration(rand.Int63n(int64(duration)))
    randomDate := startDate.Add(randomDuration)

    fmt.Println(randomDate.Format("2006-01-02"))
}

Explanation:

First, we need to set the start and end date. We can use the time.Date function to create time.Time values that represent the start and end dates.

The first step in generating a random date between two dates is to set the start and end dates. We can use the time.Date function to create time.Time values that represent the start and end dates.

startDate := time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC)
endDate := time.Date(2022, 12, 31, 0, 0, 0, 0, time.UTC)

In the above program, we set the start date to January 1st, 2022 and the end date to December 31st, 2022. We use time.UTC to set the time zone to UTC, but you can set any time zone you prefer.

Next, we need to calculate the time duration between the start and end dates. We can do this by subtracting the start date from the end date, which gives us a time.Duration value representing the number of nanoseconds between the two dates.

duration := endDate.Sub(startDate)

Now, we have the time duration between start and end dates. Now we have to generate a random number within that duration. This can be done by using the math/rand package.

We can then use that random number to calculate a new time.Time value that falls within the range of the start and end dates.

randomDuration := time.Duration(rand.Int63n(int64(duration)))
randomDate := startDate.Add(randomDuration)

Finally, We then format the date using the Format method to print it in the YYYY-MM-DD format.

fmt.Println(randomDate.Format("2006-01-02"))

Categorized in:

Tagged in: