// 获取当前日期 对象 类型为 time.Time now = time.Now() fmt.Println(now) // 获取当前日期 对象 的 年 月 日 时 分 秒 时间戳 fmt.Println(now.Year()) fmt.Println(now.Month()) fmt.Println(now.Day()) fmt.Println(now.Hour()) fmt.Println(now.Minute()) fmt.Println(now.Second()) fmt.Println(now.Unix()) // 获取当前日期对象格式化 fmt.Println(now.Format("2006-01-02 15:04:05")) // 指定时间戳 转 日期 对象 类型为 time.Time fmt.Println("指定时间戳 转 日期", time.Unix(1446425371, 0)) // 指定日期 转 时间戳 setDate := "2015-03-02 12:02:03" dateFormate := "2006-01-02 15:04:05" loc, _ := time.LoadLocation("Local") //重要:获取时区 timeObj, err := time.ParseInLocation(dateFormate, setDate, loc) //指定日期 转 当地 日期对象 类型为 time.Time if err != nil { fmt.Println("parse time failed err :", err) return } fmt.Printf("%T\n", timeObj) fmt.Println(timeObj) fmt.Println(timeObj.Unix()) fmt.Println(timeObj.Year()) fmt.Println(timeObj.Month()) //指定日期格式化 fmt.Println(timeObj.Format("2006-01-02")) now = time.Now() fmt.Println(now) //时间加 一天 fmt.Println(now.Add(24 * time.Hour)) //时间减 一天 fmt.Println(now.Add(-24 * time.Hour)) // UTC 转 CST 世界日期对象 转 中国 日期对象 now = now.UTC() fmt.Println(now) // CST 转 UTC 中国 日期对象 转 界日期对象 dateF := now.Format("2006-01-02 15:04:05") //loc, _ := time.LoadLocation("Asia/hanghai") fmt.Println(time.ParseInLocation(dateFormate, dateF, loc)) // Sub 两个时间相减 //loc, _ := time.LoadLocation("Asia/hanghai") //重要:获取时区 nextYear, err1 := time.ParseInLocation(dateFormate, setDate, loc) //指定日期 转 当地 日期对象 类型为 time.Time if err1 != nil { fmt.Println("parse time failed err :", err) return } now = time.Now() d1 := nextYear.Sub(now) fmt.Println(d1)