You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.1 KiB

  1. package common
  2. import (
  3. "strings"
  4. "time"
  5. "github.com/pkg/errors"
  6. )
  7. // TimeLayout helps to parse a date string of the format YYYY-MM-DD
  8. // Intended to be used with the following function:
  9. // time.Parse(TimeLayout, date)
  10. var TimeLayout = "2006-01-02" //this represents YYYY-MM-DD
  11. // ParseDateRange parses a date range string of the format start:end
  12. // where the start and end date are of the format YYYY-MM-DD.
  13. // The parsed dates are time.Time and will return the zero time for
  14. // unbounded dates, ex:
  15. // unbounded start: :2000-12-31
  16. // unbounded end: 2000-12-31:
  17. func ParseDateRange(dateRange string) (startDate, endDate time.Time, err error) {
  18. dates := strings.Split(dateRange, ":")
  19. if len(dates) != 2 {
  20. err = errors.New("bad date range, must be in format date:date")
  21. return
  22. }
  23. parseDate := func(date string) (out time.Time, err error) {
  24. if len(date) == 0 {
  25. return
  26. }
  27. out, err = time.Parse(TimeLayout, date)
  28. return
  29. }
  30. startDate, err = parseDate(dates[0])
  31. if err != nil {
  32. return
  33. }
  34. endDate, err = parseDate(dates[1])
  35. if err != nil {
  36. return
  37. }
  38. return
  39. }