习惯了IOS时间格式化的方式,在go语言开发的时候,在Go语言开发的时候竟然为格式化时间还查了半天资料,看完资料之后,才知道原来go语言时间格式化真心简单
生成时间戳
import "time"
func main {
t := time.Now()
fmt.Println("t:”,t.Unix())
}
t:1498017149
生成毫秒自己去换算,最好自己写一个工具类
当前时间
import (
"fmt"
"time"
)
func main() {
GetNowTime()
}
func GetNowTime() {
fmt.Println("This is my first go")
nowTime := time.Now()
fmt.Println(nowTime)
t := nowTime.String()
timeStr := t[:19]
fmt.Println(timeStr)
}
输出:
2018-01-10 18:41:32.239449 +0800 CST m=+0.000353463
2018-01-10 18:41:32
时间格式化
func GetTime() 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)
fmt.Println(t)
return str
}
字符串转时间戳
func main() {
x := "2018-01-09 20:24:20"
p, _ := time.Parse("2006-01-02 15:04:05", x)
fmt.Println(p.Unix())
}
output:1515529460
秒、纳秒、毫秒
func main() {
//testAes()
//testDes()
now := time.Now()
second := now.Unix()
Nanoseconds := now.UnixNano()
Millisecond := Nanoseconds / 1000000
fmt.Printf("second:%d,millisecond:%d,Millisecond:%d", second, Nanoseconds, Millisecond)
}
时间字符串转换成Time
不带时区,返回UTC time
func GetTimeFromStr() {
const format = "2006-01-02 15:04:05"
timeStr := "2018-01-09 20:24:20"
p, err := time.Parse(format, timeStr)
if err == nil {
fmt.Println(p)
}
}
带时区匹配,匹配当前时区的时间
func GetTimeFromStrLoc() {
loc, _ := time.LoadLocation("Asia/Shanghai")
const longForm = "Jan 2, 2006 at 3:04pm (MST)"
t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
fmt.Println(t)
// Note: without explicit zone, returns time in given location.
const shortForm = "2006-Jan-02"
t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
fmt.Println(t)
}
网友评论