timeutil.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. package timeutil
  10. import (
  11. "fmt"
  12. "strconv"
  13. "time"
  14. )
  15. /*
  16. MakeTimestamp creates a timestamp string based on the systems
  17. epoch (January 1, 1970 UTC).
  18. */
  19. func MakeTimestamp() string {
  20. return fmt.Sprintf("%d", time.Now().UnixNano()/int64(time.Millisecond))
  21. }
  22. /*
  23. CompareTimestamp compares 2 given timestamps. Returns 0 if they are equal,
  24. 1 if the frist is older and -1 if the second is older.
  25. */
  26. func CompareTimestamp(ts1, ts2 string) (int, error) {
  27. if ts1 == ts2 {
  28. return 0, nil
  29. }
  30. millis1, err := strconv.ParseInt(ts1, 10, 64)
  31. if err != nil {
  32. return 0, err
  33. }
  34. millis2, err := strconv.ParseInt(ts2, 10, 64)
  35. if err != nil {
  36. return 0, err
  37. }
  38. if millis1 < millis2 {
  39. return 1, nil
  40. }
  41. return -1, nil
  42. }
  43. /*
  44. TimestampString prints a given timestamp as a human readable time in a given
  45. Location (timezone).
  46. */
  47. func TimestampString(ts, loc string) (string, error) {
  48. millis, err := strconv.ParseInt(ts, 10, 64)
  49. if err != nil {
  50. return "", err
  51. }
  52. tsTime := time.Unix(0, millis*1000000)
  53. l, err := time.LoadLocation(loc)
  54. if err != nil {
  55. return "", err
  56. }
  57. return tsTime.In(l).String(), nil
  58. }