time
包提供了时间日期操作的函数, 包括时间的显示和计算.导入方式为 import "time"
常用类型定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| type Weekday int
type Month int
type Location struct { }
type Time struct { }
type Duration int64
|
常用内置常量及变量
time
包中提供了如下常用常量或变量的定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
const ( January Month = 1 + iota February March April May June July August September October November December ) const ( Sunday Weekday = iota Monday Tuesday Wednesday Thursday Friday Saturday ) const ( Nanosecond Duration = 1 Microsecond = 1000 * Nanosecond Millisecond = 1000 * Microsecond Second = 1000 * Millisecond Minute = 60 * Second Hour = 60 * Minute ) var UTC *Location = &utcLoc var Local *Location = &localLoc
|
常用函数
time
包函数
1 2 3 4 5 6 7 8 9
| func Now() Time
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
func Parse(layout, value string) (Time, error)
func Sleep(d Duration)
|
Time
结构体方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| func (t Time) Format(layout string) string
func (t Time) Unix() int64
func (t Time) UnixNano() int64
func (t Time) UTC() Time
func (t Time) Date() (year int, month Month, day int)
func (t Time) Clock() (hour, min, sec int)
func (t Time) Add(d Duration) Time
func (t Time) AddDate(years int, months int, days int) Time
func (t Time) Year() int
func (t Time) Month() Month
func (t Time) Day() int
func (t Time) YearDay() int
func (t Time) Hour() int
func (t Time) Minute() int
func (t Time) Second() int
func (t Time) Nanosecond() int
func (t Time) Weekday() Weekday
func (t Time) Location() *Location
func (t Time) Zone() (name string, offset int)
func (t Time) After(u Time) bool
func (t Time) Before(u Time) bool
func (t Time) Equal(u Time) bool
func (t Time) Sub(u Time) Duration
|
示例
时间日志对象与字符串相互转换示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import ( "fmt" "time" )
func main() { now := time.Now() nowStr := now.Format("2006-01-02 15:04:05")
fmt.Println(nowStr) str := "2020年5月1日 15" t := time.Parse("2006年1月2日", str) fmt.Printf("%v, %T\n", t, t)
|