date.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package sprig
  2. import (
  3. "strconv"
  4. "time"
  5. )
  6. // Given a format and a date, format the date string.
  7. //
  8. // Date can be a `time.Time` or an `int, int32, int64`.
  9. // In the later case, it is treated as seconds since UNIX
  10. // epoch.
  11. func date(fmt string, date interface{}) string {
  12. return dateInZone(fmt, date, "Local")
  13. }
  14. func htmlDate(date interface{}) string {
  15. return dateInZone("2006-01-02", date, "Local")
  16. }
  17. func htmlDateInZone(date interface{}, zone string) string {
  18. return dateInZone("2006-01-02", date, zone)
  19. }
  20. func dateInZone(fmt string, date interface{}, zone string) string {
  21. var t time.Time
  22. switch date := date.(type) {
  23. default:
  24. t = time.Now()
  25. case time.Time:
  26. t = date
  27. case *time.Time:
  28. t = *date
  29. case int64:
  30. t = time.Unix(date, 0)
  31. case int:
  32. t = time.Unix(int64(date), 0)
  33. case int32:
  34. t = time.Unix(int64(date), 0)
  35. }
  36. loc, err := time.LoadLocation(zone)
  37. if err != nil {
  38. loc, _ = time.LoadLocation("UTC")
  39. }
  40. return t.In(loc).Format(fmt)
  41. }
  42. func dateModify(fmt string, date time.Time) time.Time {
  43. d, err := time.ParseDuration(fmt)
  44. if err != nil {
  45. return date
  46. }
  47. return date.Add(d)
  48. }
  49. func dateAgo(date interface{}) string {
  50. var t time.Time
  51. switch date := date.(type) {
  52. default:
  53. t = time.Now()
  54. case time.Time:
  55. t = date
  56. case int64:
  57. t = time.Unix(date, 0)
  58. case int:
  59. t = time.Unix(int64(date), 0)
  60. }
  61. // Drop resolution to seconds
  62. duration := time.Since(t).Round(time.Second)
  63. return duration.String()
  64. }
  65. func toDate(fmt, str string) time.Time {
  66. t, _ := time.ParseInLocation(fmt, str, time.Local)
  67. return t
  68. }
  69. func unixEpoch(date time.Time) string {
  70. return strconv.FormatInt(date.Unix(), 10)
  71. }