在代码中我们可以使用Format方法来进行日期的格式化,那么在template文件,比如tpl文件中如何格式化日期呢?本篇文章给大家提供相关实例
例如结果体Post代码如下:
type Post struct {
Id int
Title string
CreatedOn time.Time
}
//数据库中存储的日期为 2015-04-04 20:51:48
那么,在页面template中可通过如下方式获取:
<span>{{ .CreatedOn }}</span>
<!-- 输出: 2015-04-04 20:51:48 +0000 +0000 -->
<span>{{ .CreatedOn.Format "2006 Jan 02" }}</span>
<!-- 输出: 2015 Apr 04 -->
<span>{{ .CreatedOn.Format "Jan 02, 2006" }}</span>
<!-- 输出: Apr 04, 2015 -->
<span>{{.CreatedOn.Format "Jan 02, 2006 15:04:05 UTC" }}</span>
<!-- 输出: Apr 04, 2015 20:51:48 UTC -->
在使用此格式化的过程中需要注意的是Format后面所跟的常量字符串,必须是示例中的时间。具体的时间常量可以参考time包下format.go文件内定义的常量:
const (
ANSIC = "Mon Jan _2 15:04:05 2006"
UnixDate = "Mon Jan _2 15:04:05 MST 2006"
RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
RFC822 = "02 Jan 06 15:04 MST"
RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
RFC3339 = "2006-01-02T15:04:05Z07:00"
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
Kitchen = "3:04PM"
// Handy time stamps.
Stamp = "Jan _2 15:04:05"
StampMilli = "Jan _2 15:04:05.000"
StampMicro = "Jan _2 15:04:05.000000"
StampNano = "Jan _2 15:04:05.000000000"
)