time.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package util
  2. import (
  3. "fmt"
  4. "strconv"
  5. "time"
  6. )
  7. const (
  8. MinsPerHour = 60.0
  9. HoursPerDay = 24.0
  10. HoursPerMonth = 730.0
  11. DaysPerMonth = 30.42
  12. )
  13. // ParseDuration converts a Prometheus-style duration string into a Duration
  14. func ParseDuration(duration string) (*time.Duration, error) {
  15. unitStr := duration[len(duration)-1:]
  16. var unit time.Duration
  17. switch unitStr {
  18. case "s":
  19. unit = time.Second
  20. case "m":
  21. unit = time.Minute
  22. case "h":
  23. unit = time.Hour
  24. case "d":
  25. unit = 24.0 * time.Hour
  26. default:
  27. return nil, fmt.Errorf("error parsing duration: %s did not match expected format [0-9+](s|m|d|h)", duration)
  28. }
  29. amountStr := duration[:len(duration)-1]
  30. amount, err := strconv.ParseInt(amountStr, 10, 64)
  31. if err != nil {
  32. return nil, fmt.Errorf("error parsing duration: %s did not match expected format [0-9+](s|m|d|h)", duration)
  33. }
  34. dur := time.Duration(amount) * unit
  35. return &dur, nil
  36. }
  37. // ParseTimeRange returns a start and end time, respectively, which are converted from
  38. // a duration and offset, defined as strings with Prometheus-style syntax.
  39. func ParseTimeRange(duration, offset string) (*time.Time, *time.Time, error) {
  40. // endTime defaults to the current time, unless an offset is explicity declared,
  41. // in which case it shifts endTime back by given duration
  42. endTime := time.Now()
  43. if offset != "" {
  44. o, err := ParseDuration(offset)
  45. if err != nil {
  46. return nil, nil, fmt.Errorf("error parsing offset (%s): %s", offset, err)
  47. }
  48. endTime = endTime.Add(-1 * *o)
  49. }
  50. // if duration is defined in terms of days, convert to hours
  51. // e.g. convert "2d" to "48h"
  52. durationNorm, err := normalizeTimeParam(duration)
  53. if err != nil {
  54. return nil, nil, fmt.Errorf("error parsing duration (%s): %s", duration, err)
  55. }
  56. // convert time duration into start and end times, formatted
  57. // as ISO datetime strings
  58. dur, err := time.ParseDuration(durationNorm)
  59. if err != nil {
  60. return nil, nil, fmt.Errorf("errorf parsing duration (%s): %s", durationNorm, err)
  61. }
  62. startTime := endTime.Add(-1 * dur)
  63. return &startTime, &endTime, nil
  64. }
  65. func normalizeTimeParam(param string) (string, error) {
  66. // convert days to hours
  67. if param[len(param)-1:] == "d" {
  68. count := param[:len(param)-1]
  69. val, err := strconv.ParseInt(count, 10, 64)
  70. if err != nil {
  71. return "", err
  72. }
  73. val = val * 24
  74. param = fmt.Sprintf("%dh", val)
  75. }
  76. return param, nil
  77. }