How to calculate sundays between two dates in Golang 1.20
In this video we are going to generate source code for the GoLang Program, How to calculate sundays between two dates using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
##############SOURCE CODE#########################
package main
import (
"fmt"
"time"
)
func main() {
// Dates to compare
date1 := time.Date(2022, time.January, 1, 0, 0, 0, 0, time.UTC)
date2 := time.Date(2022, time.January, 3, 0, 0, 0, 0, time.UTC)
// Count number of Sundays
numSundays := 0
for d := date1; d.Before(date2); d = d.AddDate(0, 0, 1) {
if d.Weekday() == time.Sunday {
numSundays++
}
}
// Print result
fmt.Printf("There are %d Sundays between %v and %v\n", numSundays, date1, date2)
}
Below is the explanation for the program:
The program uses the time package to represent the two dates that we want to compare.
In this example, we're comparing all Sundays between January 1st, 2022 and January 1st, 2023.
We use a for loop to iterate over each day between date1 and date2,
using the AddDate method of the time.Time type to add one day to the current date in each iteration.
We then use the Weekday method to check if the current date is a Sunday, and increment the numSundays variable if it is.
Finally, we print the number of Sundays using the fmt.Printf function.
You can modify the program to count the number of Sundays between any two dates you want by changing the date1 and date2 variables.
#go #goprogramming #golang #golangtutorial #golanguage