golang标准库time学习
  Adknp2DJyaqB 2023年11月02日 31 0

golang标准库time学习

新建 time.go

package time

import (
	"fmt"
	"time"
)

const (
	LHour = "15"
)

func TimeFunc() {
	//返回当前当地时间
	t := time.Now()
	fmt.Println(t)          //返回string time
	fmt.Println(t.String()) //返回string time
	fmt.Println(t.UTC())    //返回uinx time
	fmt.Println(t.Hour())   //返回小时
	y, m, d := t.Date()     //返回年月日
	fmt.Println(y)
	fmt.Println(m)
	fmt.Println(d)
	fmt.Println(t.Unix())      //返回秒
	fmt.Println(t.UnixNano())  //返回纳秒
	fmt.Println(t.UnixMicro()) //返回微秒
	fmt.Println(t.UnixMilli()) //返回毫秒

	//获取时间的时分秒
	ho, mi, se := t.Clock()
	fmt.Println(ho)
	fmt.Println(mi)
	fmt.Println(se)

	//比较时间先后
	ttt := t.Compare(time.Now())
	fmt.Println(ttt)
	//获取天
	day := t.Day()
	fmt.Println(day)
	//比较时间是否相等
	tf1 := time.Now()
	tft := t.Equal(tf1)
	fmt.Println(tft)
	//打印golang源代码
	fmt.Println(t.GoString())
	//当前时间字节数组
	gobe, _ := t.GobEncode()
	fmt.Println(gobe)
	//时间字节数组转时间
	t.GobDecode(gobe)
	fmt.Println(t)
	//获取iso年/周
	yyy, wee := t.ISOWeek()
	fmt.Println(yyy)
	fmt.Println(wee)
	//判断时间是否0时
	isZero := t.IsZero()
	fmt.Println(isZero)
	//获取本地时间
	fmt.Println(t.Local())
	//返回时间时区信息
	locaation := t.Location()
	fmt.Println(locaation)
	//返回字节数组
	tbyte, _ := t.MarshalBinary()
	fmt.Println(tbyte)
	fmt.Println(t.UnmarshalBinary(tbyte))
	jbyte, _ := t.MarshalJSON()
	fmt.Println(jbyte)
	fmt.Println(t.UnmarshalJSON(jbyte))
	xbyte, _ := t.MarshalText()
	fmt.Println(xbyte)
	fmt.Println(t.UnmarshalText(xbyte))

	//返回英文周
	fmt.Println(t.Weekday())

	fmt.Println(t.Zone())
	fmt.Println(t.ZoneBounds())

	round := []time.Duration{
		time.Nanosecond,
		time.Microsecond,
		time.Millisecond,
		time.Second,
		2 * time.Second,
		time.Minute,
		10 * time.Minute,
		time.Hour,
	}

	for _, d := range round {
		fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999"))
	}

	fmt.Println(t.String())

	difference := t.Sub(tf1)
	fmt.Printf("difference = %v\n", difference)
	//持续时间或者时间间隔
	pd, _ := time.ParseDuration("5h40m20s")
	pe, _ := time.ParseDuration("1h40m20s")
	fmt.Println(pd)                //字符串打印
	fmt.Println(pd.String())       //字符串打印
	fmt.Println(pd.Seconds())      //间隔秒
	fmt.Println(pd.Abs())          //打印
	fmt.Println(pd.Hours())        //间隔小时
	fmt.Println(pd.Microseconds()) //间隔微秒
	fmt.Println(pd.Milliseconds()) //间隔毫秒
	fmt.Println(pd.Minutes())      //间隔分钟
	fmt.Println(pd.Nanoseconds())  //间隔纳秒
	fmt.Println(pd.Round(pe))      //pe超过可存储最大值,返回可存储最大值。如果pe<= 0,返回pe
	fmt.Println(pd.Truncate(pe))

	//确定北京时区
	secondsEastOfUTC := int((8 * time.Hour).Seconds())
	beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
	//utc时间
	timeInUTC := time.Date(2023, 10, 16, 12, 0, 0, 0, time.UTC)
	//北京时间
	sameTimeInBeijing := time.Date(2023, 10, 16, 12, 0, 0, 0, beijing)
	fmt.Println(timeInUTC)
	fmt.Println(sameTimeInBeijing)

	//将字符串时间解析为time
	layout := "2006-01-02T15:04:05Z"
	str := "2023-10-16T08:30:45Z"
	parse, _ := time.Parse(layout, str)
	fmt.Println(parse)

	//返回字符串时间当地time
	loc, _ := time.LoadLocation("Europe/Berlin")
	const longForm = "Jan 2, 2006 at 3:04pm (MST)"
	parseLoc, _ := time.ParseInLocation(longForm, "Jul 9, 2023 at 5:02am (CEST)", loc)
	fmt.Println(parseLoc)
	const shortForm = "2006-Jan-02"
	parseLoc1, _ := time.ParseInLocation(shortForm, "2023-Jul-09", loc)
	fmt.Println(parseLoc1)

	//定位失时区
	lot := time.FixedZone("UTC-8", -8*60*60)
	tf := time.Date(2023, 10, 18, 23, 0, 0, 0, lot)
	fmt.Println("The time is:", tf)

	//按指定失去打印
	location, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		panic(err)
	}
	timeInUTC = time.Date(2023, 10, 18, 12, 0, 0, 0, time.UTC)
	fmt.Println(timeInUTC.In(location))

	//比较时间前后
	year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
	year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
	isYear3000AfterYear2000 := year3000.After(year2000) // True
	isYear2000AfterYear3000 := year2000.After(year3000) // False
	fmt.Printf("year3000.After(year2000) = %v\n", isYear3000AfterYear2000)
	fmt.Printf("year2000.After(year3000) = %v\n", isYear2000AfterYear3000)
	year2000 = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
	year3000 = time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
	isYear2000BeforeYear3000 := year2000.Before(year3000) // True
	isYear3000BeforeYear2000 := year3000.Before(year2000) // False
	fmt.Printf("year2000.Before(year3000) = %v\n", isYear2000BeforeYear3000)
	fmt.Printf("year3000.Before(year2000) = %v\n", isYear3000BeforeYear2000)

	appentformant := time.Now()
	textTime := []byte("Time: ")
	textHour := []byte("Hour: ")
	textTime = appentformant.AppendFormat(textTime, time.Kitchen)
	textHour = appentformant.AppendFormat(textHour, LHour)
	fmt.Println(string(textTime))
	fmt.Println(string(textHour))

	//timer定时器  只执行一次
	timer := time.NewTimer(time.Second * 3)
	defer timer.Stop()
	done := make(chan bool)
	go func() {
		time.Sleep(10 * time.Second)
		done <- true
	}()
	for {
		//
		timer.Reset(time.Second * 3)
		select {
		case <-done:
			fmt.Println("Done!")
			break
		case ttttt := <-timer.C:
			fmt.Println(ttttt)
		}
	}

	timerChannel := time.After(time.Second * 5)
	select {
	case ttttt := <-timerChannel:
		fmt.Println(ttttt)
	}

	//定时器
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()
	done1 := make(chan bool)
	go func() {
		time.Sleep(10 * time.Second)
		done <- true
	}()
	ticker.Reset(time.Second * 2)
	for {
		select {
		case <-done1:
			fmt.Println("Done1!")
			break
		case t := <-ticker.C:
			fmt.Println("Current time: ", t)
		}
	}

}

然后新建time_test.go

package time

import "testing"

func TestTimeFunc(t *testing.T) {
	TimeFunc()
}

然后执行

go test -v
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  jE8iBWyhLcsg   2023年11月02日   46   0   0 javasubstringgolang
  Adknp2DJyaqB   2023年11月02日   56   0   0 unsafegolang
  Adknp2DJyaqB   2023年11月02日   35   0   0 unicodegolang
  Ohl6n170bzPf   2023年11月02日   26   0   0 golang
  Adknp2DJyaqB   2023年11月13日   20   0   0 restfulgrpcgolang
  Adknp2DJyaqB   2023年11月13日   30   0   0 发布订阅grpcgolang
  Adknp2DJyaqB   2023年11月02日   32   0   0 golang
  Adknp2DJyaqB   2023年11月02日   33   0   0 golangmilvus
  Adknp2DJyaqB   2023年11月13日   23   0   0 grpcgolang
Adknp2DJyaqB