1. 程式人生 > >golang TIME 時間獲取時間轉換

golang TIME 時間獲取時間轉換

func Get_time()string{//獲取當前時間

QQ29295842

//now:=time.Now()
//year,mon,day:=now.UTC().Date()
//hour,min,sec:=now.UTC().Clock()
//zone,_:=now.UTC().Zone()
//fmt.Printf("UTCtimeis%d-%d-%d%02d:%02d:%02d%s\n",
//year,mon,day,hour,min,sec,zone)
now:=time.Now()
year,mon,day:=now.Date()
hour,min,sec:=now.Clock()
//zone,_=now.Zone()
//fmt.Printf("localtimeis%d-%d-%d%02d:%02d:%02d%s\n",
//year,mon,day,hour,min,sec,zone)
returnfmt.Sprintf("%d-%d-%d%02d:%02d:%02d",year,mon,day,hour,min,sec)
}

golang時間處理
相關包 "time"

  • 時間戳 
    當前時間戳

    fmt.Println(time.Now().Unix())
    # 1389058332
  • str格式化時間
    當前格式化時間

    fmt.Println(time.Now().Format("2006-01-02 15:04:05"))  // 這是個奇葩,必須是這個時間點, 據說是go誕生之日, 記憶方法:6-1-2-3-4-5
    # 2014-01-07 09:42:20
  • 時間戳轉str格式化時間

    str_time := time.Unix(1389058332, 0).Format("2006-01-02 15:04:05")
    fmt.Println(str_time)
    # 2014-01-07 09:32:12
  • str格式化時間轉時間戳
    這個比較麻煩

    the_time := time.Date(2014, 1, 7, 5, 50, 4, 0, time.Local)
    unix_time := the_time.Unix()
    fmt.Println(unix_time)
    # 389045004

    還有一種方法,使用time.Parse

    the_time, err := time.Parse("2006-01-02 15:04:05", "2014-01-08 09:04:41")
    if err == nil {
            unix_time := the_time.Unix()
    	fmt.Println(unix_time)		
    }
    # 1389171881
  • ing