utils.go 646 B

1234567891011121314151617181920212223242526272829
  1. package timeutils
  2. import (
  3. "strconv"
  4. "strings"
  5. "time"
  6. )
  7. // GetTimestamp tries to parse given string as RFC3339 time
  8. // or Unix timestamp (with seconds precision), if successful
  9. //returns a Unix timestamp as string otherwise returns value back.
  10. func GetTimestamp(value string) string {
  11. var format string
  12. if strings.Contains(value, ".") {
  13. format = time.RFC3339Nano
  14. } else {
  15. format = time.RFC3339
  16. }
  17. loc := time.FixedZone(time.Now().Zone())
  18. if len(value) < len(format) {
  19. format = format[:len(value)]
  20. }
  21. t, err := time.ParseInLocation(format, value, loc)
  22. if err != nil {
  23. return value
  24. }
  25. return strconv.FormatInt(t.Unix(), 10)
  26. }