Created
July 1, 2022 14:36
-
-
Save stokito/d1ddae25922ee3338273c1544b6980ea to your computer and use it in GitHub Desktop.
Start-End date parsing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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