duration.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (c) 2017 Hervé Gouchet. All rights reserved.
  2. // Use of this source code is governed by the MIT License
  3. // that can be found in the LICENSE file.
  4. package duration
  5. import (
  6. "math"
  7. "time"
  8. "github.com/miniflux/miniflux/locale"
  9. )
  10. // Texts to be translated if necessary.
  11. var (
  12. NotYet = `not yet`
  13. JustNow = `just now`
  14. LastMinute = `1 minute ago`
  15. Minutes = `%d minutes ago`
  16. LastHour = `1 hour ago`
  17. Hours = `%d hours ago`
  18. Yesterday = `yesterday`
  19. Days = `%d days ago`
  20. Weeks = `%d weeks ago`
  21. Months = `%d months ago`
  22. Years = `%d years ago`
  23. )
  24. // ElapsedTime returns in a human readable format the elapsed time
  25. // since the given datetime.
  26. func ElapsedTime(translator *locale.Language, t time.Time) string {
  27. if t.IsZero() || time.Now().Before(t) {
  28. return translator.Get(NotYet)
  29. }
  30. diff := time.Since(t)
  31. // Duration in seconds
  32. s := diff.Seconds()
  33. // Duration in days
  34. d := int(s / 86400)
  35. switch {
  36. case s < 60:
  37. return translator.Get(JustNow)
  38. case s < 120:
  39. return translator.Get(LastMinute)
  40. case s < 3600:
  41. return translator.Get(Minutes, int(diff.Minutes()))
  42. case s < 7200:
  43. return translator.Get(LastHour)
  44. case s < 86400:
  45. return translator.Get(Hours, int(diff.Hours()))
  46. case d == 1:
  47. return translator.Get(Yesterday)
  48. case d < 7:
  49. return translator.Get(Days, d)
  50. case d < 31:
  51. return translator.Get(Weeks, int(math.Ceil(float64(d)/7)))
  52. case d < 365:
  53. return translator.Get(Months, int(math.Ceil(float64(d)/30)))
  54. default:
  55. return translator.Get(Years, int(math.Ceil(float64(d)/365)))
  56. }
  57. }