golong 时间戳、时间字符串、时间格式之间转换

一、字符串格式时间戳转换为时间戳格式(string -> int64)

	//字符串格式时间戳转换为字符戳格式(string -> int64)
	timeString := "1636275830000"
	timeUnix, _ := strconv.ParseInt(timeString, 10, 64)
	fmt.Printf("timeString值为:%s,类型为%T\n",timeString,timeString)	    //timeString值为:1636275830000,类型为string
	fmt.Printf("timeUnix值为:%d,类型为%T\n",timeUnix,timeUnix)		//timeUnix值为:1636275830000,类型为int64

二、时间戳格式转时间字符串 (int64 —> string)

  注意:Format里面只能是 "2006-01-02 15:04:05" (go的诞生时间)

  各种格式模板如下:

    "2006-01-02 15:04:05"
    "2006/01/02 15:04:05" 
    "2006-01-02" 
    "15:04:05" 

	//时间戳转时间字符串 (int64 —> string)
	var timeUnix int64
	timeUnix = 1636275830000
	formatTimeStr := time.Unix(timeUnix/1e3, 0).Format("2006-01-02 15:04:05")
	fmt.Println(formatTimeStr) 	// 2021-11-07 17:03:50

三、时间字符串转时间(string —> Time)

	// 时间字符串转时间(string —> Time)
	timeString := "2021-11-07 17:03:50"
	formatTime,err:=time.Parse("2006-01-02 15:04:05",timeString)
	if err != nil{
		fmt.Println("错误")
	}
	fmt.Printf("formatTime类型为:%T\n",formatTime)	//formatTime类型为:time.Time
	fmt.Println("formatTime值为:",formatTime) //formatTime值为: 2021-11-07 17:03:50 +0000 UTC

四、时间转时间戳(Time -> int64)

	//时间转时间戳(Time -> int64)
	timeTime :=	time.Now()
	fmt.Println(timeTime.Unix())	//1636283446
posted @ 2021-11-07 19:13  非帆丶  阅读(198)  评论(0编辑  收藏  举报