diff.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package moment
  2. import (
  3. "fmt"
  4. "math"
  5. "time"
  6. )
  7. // @todo In months/years requires the old and new to calculate correctly, right?
  8. // @todo decide how to handle rounding (i.e. always floor?)
  9. type Diff struct {
  10. duration time.Duration
  11. }
  12. func (d *Diff) InSeconds() int {
  13. return int(d.duration.Seconds())
  14. }
  15. func (d *Diff) InMinutes() int {
  16. return int(d.duration.Minutes())
  17. }
  18. func (d *Diff) InHours() int {
  19. return int(d.duration.Hours())
  20. }
  21. func (d *Diff) InDays() int {
  22. return int(math.Floor(float64(d.InSeconds()) / 86400))
  23. }
  24. // This depends on where the weeks fall?
  25. func (d *Diff) InWeeks() int {
  26. return int(math.Floor(float64(d.InDays() / 7)))
  27. }
  28. func (d *Diff) InMonths() int {
  29. return 0
  30. }
  31. func (d *Diff) InYears() int {
  32. return 0
  33. }
  34. // http://momentjs.com/docs/#/durations/humanize/
  35. func (d *Diff) Humanize() string {
  36. diffInSeconds := d.InSeconds()
  37. if diffInSeconds <= 45 {
  38. return fmt.Sprintf("%d seconds ago", diffInSeconds)
  39. } else if diffInSeconds <= 90 {
  40. return "a minute ago"
  41. }
  42. diffInMinutes := d.InMinutes()
  43. if diffInMinutes <= 45 {
  44. return fmt.Sprintf("%d minutes ago", diffInMinutes)
  45. } else if diffInMinutes <= 90 {
  46. return "an hour ago"
  47. }
  48. diffInHours := d.InHours()
  49. if diffInHours <= 22 {
  50. return fmt.Sprintf("%d hours ago", diffInHours)
  51. } else if diffInHours <= 36 {
  52. return "a day ago"
  53. }
  54. return "diff is in days"
  55. }
  56. // In Months
  57. // In years