2023-04-23 19:12:33 +00:00
|
|
|
// Copyright 2023 The Gitea Authors. All rights reserved.
|
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
|
|
|
|
package timeutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"html"
|
|
|
|
"html/template"
|
2024-01-02 01:25:30 +00:00
|
|
|
"strings"
|
2023-04-25 19:48:30 +00:00
|
|
|
"time"
|
2023-04-23 19:12:33 +00:00
|
|
|
)
|
|
|
|
|
2023-04-25 19:48:30 +00:00
|
|
|
// DateTime renders an absolute time HTML element by datetime.
|
2024-11-02 21:04:53 +00:00
|
|
|
func DateTime(format string, datetime any) template.HTML {
|
2023-04-25 19:48:30 +00:00
|
|
|
if p, ok := datetime.(*time.Time); ok {
|
|
|
|
datetime = *p
|
|
|
|
}
|
|
|
|
if p, ok := datetime.(*TimeStamp); ok {
|
|
|
|
datetime = *p
|
|
|
|
}
|
|
|
|
switch v := datetime.(type) {
|
|
|
|
case TimeStamp:
|
|
|
|
datetime = v.AsTime()
|
|
|
|
case int:
|
|
|
|
datetime = TimeStamp(v).AsTime()
|
|
|
|
case int64:
|
|
|
|
datetime = TimeStamp(v).AsTime()
|
|
|
|
}
|
|
|
|
|
|
|
|
var datetimeEscaped, textEscaped string
|
|
|
|
switch v := datetime.(type) {
|
|
|
|
case nil:
|
2023-05-02 09:54:29 +00:00
|
|
|
return "-"
|
2023-04-25 19:48:30 +00:00
|
|
|
case time.Time:
|
|
|
|
if v.IsZero() || v.Unix() == 0 {
|
2023-05-02 09:54:29 +00:00
|
|
|
return "-"
|
2023-04-25 19:48:30 +00:00
|
|
|
}
|
|
|
|
datetimeEscaped = html.EscapeString(v.Format(time.RFC3339))
|
|
|
|
if format == "full" {
|
|
|
|
textEscaped = html.EscapeString(v.Format("2006-01-02 15:04:05 -07:00"))
|
|
|
|
} else {
|
|
|
|
textEscaped = html.EscapeString(v.Format("2006-01-02"))
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
panic(fmt.Sprintf("Unsupported time type %T", datetime))
|
|
|
|
}
|
|
|
|
|
2024-11-02 21:04:53 +00:00
|
|
|
attrs := []string{`weekday=""`, `year="numeric"`}
|
2023-04-23 19:12:33 +00:00
|
|
|
switch format {
|
2024-03-12 22:37:02 +00:00
|
|
|
case "short", "long": // date only
|
|
|
|
attrs = append(attrs, `month="`+format+`"`, `day="numeric"`)
|
2024-03-15 02:05:31 +00:00
|
|
|
return template.HTML(fmt.Sprintf(`<absolute-date %s date="%s">%s</absolute-date>`, strings.Join(attrs, " "), datetimeEscaped, textEscaped))
|
2024-03-12 22:37:02 +00:00
|
|
|
case "full": // full date including time
|
|
|
|
attrs = append(attrs, `format="datetime"`, `month="short"`, `day="numeric"`, `hour="numeric"`, `minute="numeric"`, `second="numeric"`, `data-tooltip-content`, `data-tooltip-interactive="true"`)
|
|
|
|
return template.HTML(fmt.Sprintf(`<relative-time %s datetime="%s">%s</relative-time>`, strings.Join(attrs, " "), datetimeEscaped, textEscaped))
|
2024-01-02 19:09:18 +00:00
|
|
|
default:
|
|
|
|
panic(fmt.Sprintf("Unsupported format %s", format))
|
2023-04-23 19:12:33 +00:00
|
|
|
}
|
|
|
|
}
|