golang基础--时间戳、时间字符串、时间对象相互转化

目前只是时间戳、时间字符串、时间对象相互转化
后续如果有需求,在完善该时间工具类

package main

import (
	"fmt"
	"time"
)

func main()  {

	Str2Time:=Str2Time("2017-09-12 12:03:40")
	fmt.Println(Str2Time)


	Str2Stamp:=Str2Stamp("2017-09-12 12:03:40")
	fmt.Println(Str2Stamp)

	Time2Str:=Time2Str()
	fmt.Println(Time2Str)

	GetStamp:=Time2Stamp()
	fmt.Println(GetStamp)

	Stamp2Str:=Stamp2Str(1505189020000)
	fmt.Println(Stamp2Str)

	Stamp2Time:=Stamp2Time(1505188820000)
	fmt.Println(Stamp2Time)
}

/**字符串->时间对象*/
func Str2Time(formatTimeStr string) time.Time{
	timeLayout := "2006-01-02 15:04:05"
	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation(timeLayout, formatTimeStr, loc) //使用模板在对应时区转化为time.time类型

	return theTime

}
/**字符串->时间戳*/
func Str2Stamp(formatTimeStr string) int64 {
	timeStruct:=Str2Time(formatTimeStr)
	millisecond:=timeStruct.UnixNano()/1e6
	return  millisecond
}

/**时间对象->字符串*/
func Time2Str() string {
	const shortForm = "2006-01-01 15:04:05"
	t := time.Now()
	temp := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.Local)
	str := temp.Format(shortForm)
	return str
}


/*时间对象->时间戳*/
func Time2Stamp()int64{
	t:=time.Now()
	millisecond:=t.UnixNano()/1e6
	return  millisecond
}
/*时间戳->字符串*/
func Stamp2Str(stamp int64) string{
	timeLayout := "2006-01-02 15:04:05"
	str:=time.Unix(stamp/1000,0).Format(timeLayout)
	return str
}
/*时间戳->时间对象*/
func Stamp2Time(stamp int64)time.Time{
	stampStr:=Stamp2Str(stamp)
	timer:=Str2Time(stampStr)
	return timer
}


输出如下:

2017-09-12 12:03:40 +0800 CST
1505189020000
2018-11-11 17:50:50
1541497850321
2017-09-12 12:03:40
2017-09-12 12:00:20 +0800 CST

你可能感兴趣的:(Go基础)