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