strings.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package util
  2. import (
  3. "fmt"
  4. "math"
  5. "regexp"
  6. "time"
  7. )
  8. // StringsFallback2 returns the first of two not empty strings.
  9. func StringsFallback2(val1 string, val2 string) string {
  10. return stringsFallback(val1, val2)
  11. }
  12. // StringsFallback3 returns the first of three not empty strings.
  13. func StringsFallback3(val1 string, val2 string, val3 string) string {
  14. return stringsFallback(val1, val2, val3)
  15. }
  16. func stringsFallback(vals ...string) string {
  17. for _, v := range vals {
  18. if v != "" {
  19. return v
  20. }
  21. }
  22. return ""
  23. }
  24. // SplitString splits a string by commas or empty spaces.
  25. func SplitString(str string) []string {
  26. if len(str) == 0 {
  27. return []string{}
  28. }
  29. return regexp.MustCompile("[, ]+").Split(str, -1)
  30. }
  31. // GetAgeString returns a string representing certain time from years to minutes.
  32. func GetAgeString(t time.Time) string {
  33. if t.IsZero() {
  34. return "?"
  35. }
  36. sinceNow := time.Since(t)
  37. minutes := sinceNow.Minutes()
  38. years := int(math.Floor(minutes / 525600))
  39. months := int(math.Floor(minutes / 43800))
  40. days := int(math.Floor(minutes / 1440))
  41. hours := int(math.Floor(minutes / 60))
  42. if years > 0 {
  43. return fmt.Sprintf("%dy", years)
  44. }
  45. if months > 0 {
  46. return fmt.Sprintf("%dM", months)
  47. }
  48. if days > 0 {
  49. return fmt.Sprintf("%dd", days)
  50. }
  51. if hours > 0 {
  52. return fmt.Sprintf("%dh", hours)
  53. }
  54. if int(minutes) > 0 {
  55. return fmt.Sprintf("%dm", int(minutes))
  56. }
  57. return "< 1m"
  58. }