Skip to content

Instantly share code, notes, and snippets.

@stokito
Created July 1, 2022 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stokito/d1ddae25922ee3338273c1544b6980ea to your computer and use it in GitHub Desktop.
Save stokito/d1ddae25922ee3338273c1544b6980ea to your computer and use it in GitHub Desktop.
Start-End date parsing
func handleRequest(w http.ResponseWriter, r *http.Request) {
args := r.URL.Query()
startDateStr := args.Get("start") // &start=2021-10-15
endDateStr := args.Get("end") // &end=2021-10-15
startDate := parseDate(startDateStr, "today")
endDate := parseDate(endDateStr, "tomorrow")
}
func atMidnight(startDate time.Time) time.Time {
return startDate.Truncate(24 * time.Hour).In(time.UTC)
}
func parseDate(dateStr, defaultDate string) time.Time {
if dateStr == "" {
dateStr = defaultDate
}
today := atMidnight(time.Now())
var parsedDate time.Time
if dateStr == "" || dateStr == "today" {
parsedDate = today
} else if dateStr == "yesterday" {
parsedDate = today.AddDate(0, 0, -1)
} else if dateStr == "tomorrow" {
parsedDate = today.AddDate(0, 0, 1)
} else {
// has time...
if strings.Contains(dateStr, "T") {
parsedDate, _ = time.Parse(time.RFC3339, dateStr)
} else {
parsedDate, _ = time.Parse("2006-01-02", dateStr)
}
}
return parsedDate
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment