前言
在使用go开发中,有时候需要格式化时间,go
语言的格式化时间有点特殊,使用2006-01-02 15:04:05
go格式化时间
格式化时间
go
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
a := now.Format("2006-01-02 15:04:05")
fmt.Println(a)
}
输出结果为

go
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
a := now.Format("2006-01-02")
fmt.Println(a)
}
输出结果为

go
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
a := now.Format("15:04:05")
fmt.Println(a)
}
输出结果为

可以使用中文
go
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
a := now.Format("2006年01月02日 15时04分05秒")
fmt.Println(a)
}
输出结果为

12小时制和AM/PM
go
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
a := now.Format("2006-01-02 03:04:05 PM")
fmt.Println(a)
}
输出结果为

毫秒、微秒、纳秒
go
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
a := now.Format("2006-01-02 03:04:05.000")
fmt.Println(a)
}
输出结果为

总结
time.Format()
方法的参数不是一个"模式字符串",而是一个具体的日期时间示例 。你必须使用 2006
、01
、02
、15
、04
、05
这些固定数字来代表对应的年、月、日、时、分、秒。