utils.go 975 B

123456789101112131415161718192021222324252627282930313233343536
  1. package timeutils
  2. import (
  3. "strconv"
  4. "strings"
  5. "time"
  6. )
  7. // GetTimestamp tries to parse given string as golang duration,
  8. // then RFC3339 time and finally as a Unix timestamp. If
  9. // any of these were successful, it returns a Unix timestamp
  10. // as string otherwise returns the given value back.
  11. // In case of duration input, the returned timestamp is computed
  12. // as the given reference time minus the amount of the duration.
  13. func GetTimestamp(value string, reference time.Time) string {
  14. if d, err := time.ParseDuration(value); value != "0" && err == nil {
  15. return strconv.FormatInt(reference.Add(-d).Unix(), 10)
  16. }
  17. var format string
  18. if strings.Contains(value, ".") {
  19. format = time.RFC3339Nano
  20. } else {
  21. format = time.RFC3339
  22. }
  23. loc := time.FixedZone(time.Now().Zone())
  24. if len(value) < len(format) {
  25. format = format[:len(value)]
  26. }
  27. t, err := time.ParseInLocation(format, value, loc)
  28. if err != nil {
  29. return value
  30. }
  31. return strconv.FormatInt(t.Unix(), 10)
  32. }