go随聊-time包

几乎所有的系统开发都会涉及到时间转换或者时间处理,今天介绍一下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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值