package main import ( "fmt" "time" ) func main() { t := time.Now() //time.Time time.Date(2023, time.February, 19, 14, 38, 1, 393023500, time.Local) 2023-02-19 14:38:01.3930235 +0800 CST m=+0.008177501 fmt.Printf("%T %#v %v\n", t, t, t) //2023-02-19 06:38:42.351399 +0000 UTC fmt.Printf("%v\n", t.UTC()) //time.Date(2023, time.February, 19, 6, 39, 44, 393454500, time.UTC) fmt.Printf("%#v\n", t.UTC()) //2023/02/19 14:40:40 +0800 fmt.Println(t.Format("2006/01/02 15:04:05 -0700")) //2023/02/19 14:40:40 fmt.Println(t.Format("2006/01/02 15:04:05")) //2023/02/19 06:41:41 fmt.Println(t.UTC().Format("2006/01/02 15:04:05")) println("========================") //根据字符串 格式化成时间 格式要一毛一样 timeStr := "2023#02/19\t14$42:23" parse, err := time.Parse("2006#01/02\t15$04:05", timeStr) if err != nil { fmt.Println("faile`") } else { //2023-02-19 14:42:23 +0000 UTC 注意时区 fmt.Println("success:", parse) } fmt.Println(parse.Location()) //UTC 返回parse时区 fmt.Println(parse.Local()) //2023-02-19 22:42:23 +0800 CST 时间加了8小时转到了CST //加上时区 把时间格式化成真正的当地时间和时区 loc, _ := time.LoadLocation("Asia/Shanghai") t1, err := time.ParseInLocation("2006#01/02\t15$04:05", timeStr, loc) if err != nil { fmt.Println("fail") } else { //2023-02-19 14:42:23 +0800 CST fmt.Println("t1:", t1) } //时间成分 fmt.Println( //2023 February 2 19 parse.Year(), parse.Month(), int(parse.Month()), parse.Day(), //50 parse.YearDay(), //14 42 23 parse.Hour(), parse.Minute(), parse.Second(), "\n", //时间戳 parse.Unix(), parse.UnixMilli(), parse.UnixMicro(), ) //小数部分匹配,可以使用0或9,0需要和小数部分个数匹配,9不需要 //time.Parse( // "2006/01/02 15:04:05.000 -0700", // "2008/09/08 20:36:50.123 +0800" // ) //time.Parse( // "2006/01/02 15:04:05.9 -0700", // "2008/09/08 20:36:50.1234 +0800" // ) //时间增量 println("===========") delta := t.Sub(t1) //duration类型 //5h59m18.468554s 5.988463487222222 21558.468554 5h59m18.468554s fmt.Println(delta, delta.Hours(), delta.Seconds(), delta.String()) d1 := time.Duration(3) //3纳秒 3ns fmt.Println(d1) //3s 3h0m0s fmt.Println(time.Duration(3*time.Second), time.Duration(3*time.Hour)) t2 := t1.Add(time.Duration(3 * time.Second)) //t2: 2023-02-19 14:42:26 +0800 CST fmt.Println("t2:", t2) //2023-02-19 14:42:20 +0800 CST fmt.Println(t1.Add(-time.Duration(3 * time.Second))) fmt.Println(t2.After(t)) //false fmt.Println(t2.After(t1)) //true }
标签:02,parse,fmt,2023,golang,标准,time,Println From: https://www.cnblogs.com/dribs/p/17157202.html