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.

datetime.go 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package timeutil
  4. import (
  5. "fmt"
  6. "html"
  7. "html/template"
  8. "strings"
  9. "time"
  10. )
  11. // DateTime renders an absolute time HTML element by datetime.
  12. func DateTime(format string, datetime any, extraAttrs ...string) template.HTML {
  13. if p, ok := datetime.(*time.Time); ok {
  14. datetime = *p
  15. }
  16. if p, ok := datetime.(*TimeStamp); ok {
  17. datetime = *p
  18. }
  19. switch v := datetime.(type) {
  20. case TimeStamp:
  21. datetime = v.AsTime()
  22. case int:
  23. datetime = TimeStamp(v).AsTime()
  24. case int64:
  25. datetime = TimeStamp(v).AsTime()
  26. }
  27. var datetimeEscaped, textEscaped string
  28. switch v := datetime.(type) {
  29. case nil:
  30. return "-"
  31. case string:
  32. datetimeEscaped = html.EscapeString(v)
  33. textEscaped = datetimeEscaped
  34. case time.Time:
  35. if v.IsZero() || v.Unix() == 0 {
  36. return "-"
  37. }
  38. datetimeEscaped = html.EscapeString(v.Format(time.RFC3339))
  39. if format == "full" {
  40. textEscaped = html.EscapeString(v.Format("2006-01-02 15:04:05 -07:00"))
  41. } else {
  42. textEscaped = html.EscapeString(v.Format("2006-01-02"))
  43. }
  44. default:
  45. panic(fmt.Sprintf("Unsupported time type %T", datetime))
  46. }
  47. attrs := make([]string, 0, 10+len(extraAttrs))
  48. attrs = append(attrs, extraAttrs...)
  49. attrs = append(attrs, `weekday=""`, `year="numeric"`)
  50. switch format {
  51. case "short", "long": // date only
  52. attrs = append(attrs, `month="`+format+`"`, `day="numeric"`)
  53. return template.HTML(fmt.Sprintf(`<gitea-absolute-date %s date="%s">%s</gitea-absolute-date>`, strings.Join(attrs, " "), datetimeEscaped, textEscaped))
  54. case "full": // full date including time
  55. attrs = append(attrs, `format="datetime"`, `month="short"`, `day="numeric"`, `hour="numeric"`, `minute="numeric"`, `second="numeric"`, `data-tooltip-content`, `data-tooltip-interactive="true"`)
  56. return template.HTML(fmt.Sprintf(`<relative-time %s datetime="%s">%s</relative-time>`, strings.Join(attrs, " "), datetimeEscaped, textEscaped))
  57. default:
  58. panic(fmt.Sprintf("Unsupported format %s", format))
  59. }
  60. }