You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tool.go 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package base
  5. import (
  6. "crypto/md5"
  7. "encoding/hex"
  8. "fmt"
  9. "time"
  10. )
  11. // Encode string to md5 hex value
  12. func EncodeMd5(str string) string {
  13. m := md5.New()
  14. m.Write([]byte(str))
  15. return hex.EncodeToString(m.Sum(nil))
  16. }
  17. // Seconds-based time units
  18. const (
  19. Minute = 60
  20. Hour = 60 * Minute
  21. Day = 24 * Hour
  22. Week = 7 * Day
  23. Month = 30 * Day
  24. Year = 12 * Month
  25. )
  26. // TimeSince calculates the time interval and generate user-friendly string.
  27. func TimeSince(then time.Time) string {
  28. now := time.Now()
  29. lbl := "ago"
  30. diff := now.Unix() - then.Unix()
  31. if then.After(now) {
  32. lbl = "from now"
  33. diff = then.Unix() - now.Unix()
  34. }
  35. switch {
  36. case diff <= 0:
  37. return "now"
  38. case diff <= 2:
  39. return fmt.Sprintf("1 second %s", lbl)
  40. case diff < 1*Minute:
  41. return fmt.Sprintf("%d seconds %s", diff, lbl)
  42. case diff < 2*Minute:
  43. return fmt.Sprintf("1 minute %s", lbl)
  44. case diff < 1*Hour:
  45. return fmt.Sprintf("%d minutes %s", diff/Minute, lbl)
  46. case diff < 2*Hour:
  47. return fmt.Sprintf("1 hour %s", lbl)
  48. case diff < 1*Day:
  49. return fmt.Sprintf("%d hours %s", diff/Hour, lbl)
  50. case diff < 2*Day:
  51. return fmt.Sprintf("1 day %s", lbl)
  52. case diff < 1*Week:
  53. return fmt.Sprintf("%d days %s", diff/Day, lbl)
  54. case diff < 2*Week:
  55. return fmt.Sprintf("1 week %s", lbl)
  56. case diff < 1*Month:
  57. return fmt.Sprintf("%d weeks %s", diff/Week, lbl)
  58. case diff < 2*Month:
  59. return fmt.Sprintf("1 month %s", lbl)
  60. case diff < 1*Year:
  61. return fmt.Sprintf("%d months %s", diff/Month, lbl)
  62. case diff < 18*Month:
  63. return fmt.Sprintf("1 year %s", lbl)
  64. }
  65. return then.String()
  66. }