几乎所有的系统开发都会涉及到时间转换或者时间处理,今天介绍一下go里面处理时间的包
package time
获取当前时间
//Now returns the current local time.
func Now() Time
// UTC returns t with the location set to UTC.
func (t Time) UTC() Time
// Unix returns t as a Unix time, the number of seconds elapsed
// since January 1, 1970 UTC.
func (t Time) Unix() int64
// UnixNano returns t as a Unix time, the number of nanoseconds elapsed
// since January 1, 1970 UTC. The result is undefined if the Unix time
// in nanoseconds cannot be represented by an int64 (a date before the year
// 1678 or after 2262). Note that this means the result of calling UnixNano
// on the zero Time is undefined.
func (t Time) UnixNano() int64
// Local returns t with the location set to local time.
func (t Time) Local() Time
例子:
import (
"fmt"
"time"
"testing"
)
func TestTime(t *testing.T) {
now:=time.Now()
fmt.Println(now)
utc:=now.UTC()
fmt.Println(utc)
unix:=now.Unix()
fmt.Println(unix)
unixNano:=now.UnixNano()
fmt.Println(unixNano)
local:=now.Local()
fmt.Println(local)
}
-------------------------------------------------
2018-11-02 19:52:04.3185095 +0800 CST m=+0.034002001
2018-11-02 11:52:04.3185095 +0000 UTC
1541159524
1541159524318509500
2018-11-02 19:52:04.3185095 +0800 CST
时间格式化字符串转换
func (t Time) Format(layout string) string
当前格式化时间:将当前时间转换为字符串
import (
"fmt"
"time"
"testing"
)
func TestTime(t *testing.T) {
now:=time.Now()
fmt.Println(now.Format("2006-01-02 15:04:05"))
}
-----------------------------------------------------
2018-11-02 20:02:43
时间戳转str格式化时间:
import (
"fmt"
"time"
"testing"
)
func TestTime(t *testing.T) {
//时间戳1541160241
str_time := time.Unix(1541160241, 0).Format("2006-01-02 15:04:05")
fmt.Println(str_time)
}
------------------------------------------------------------------------
2018-11-02 20:04:01
str格式化时间转时间戳:将时间转为为时间戳
import (
"fmt"
"time"
"testing"
)
func TestTime(t *testing.T) {
//时间转换为时间戳
the_time := time.Date(2018, 11, 2, 20, 4, 1, 0, time.Local)
unix_time := the_time.Unix()
fmt.Println(unix_time)
}
-------------------------------------------------------------------
1541160241