先看看有哪些类型

Time

时间类型,包含了秒和纳秒以及Location

Month

type Month int 月份.定义了十二个月的常量

Weekday

type Weekday int 周,定义了一周的七天

Duration

type Duration int64 持续时间.定义了以下持续时间类型.多用于时间的加减 需要传入Duration做为参数的时候.可以直接传入time.Second

const (
	Nanosecond  Duration = 1
	Microsecond          = 1000 * Nanosecond
	Millisecond          = 1000 * Microsecond
	Second               = 1000 * Millisecond
	Minute               = 60 * Second
	Hour                 = 60 * Minute
)

Location

在time包里有两个时区变量:

  • time.UTC utc时间
  • time.Local 本地时间

FixedZone(name string, offset int) *Location
设置时区名,以及与UTC0的时间偏差.返回Location

时间格式化

			p(t.Format("3:04PM"))
			p(t.Format("Mon Jan _2 15:04:05 2006"))
			p(t.Format("2006-01-02T15:04:05.999999-07:00"))
			p(t.Format("2006-01-02T15:04:05Z07:00"))
			fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
			t.Year(), t.Month(), t.Day(),
			t.Hour(), t.Minute(), t.Second())
		
		p := fmt.Println

		withNanos := "2006-01-02 15:04:05"
		t, _ := time.Parse(withNanos, "2013-10-05 18:30:50")
		p(t.Year())
		
			p := fmt.Println

			t, _ := time.ParseDuration("1h")
			p(t.Seconds())
		

Time相关

time常用函数

Now() Time
获取当前时间,返回Time类型
Unix(sec int64, nsec int64) Time
根据秒数和纳秒,返回Time类型
Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
设置年月日返回,Time类型
Since(t Time) Duration
返回与当前时间的时间差

time常用方法

		func main() {
		    now := time.Now()
		    secs := now.Unix()
		    nanos := now.UnixNano()
		    fmt.Println(now)
		    millis := nanos / 1000000

		    fmt.Println(secs)
		    fmt.Println(millis)
		    fmt.Println(nanos)

		    fmt.Println(time.Unix(secs, 0))
		    fmt.Println(time.Unix(0, nanos))
		}