日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

golang中日期操作之日期格式化及日期轉(zhuǎn)換_Golang

作者:Leo?Han ? 更新時(shí)間: 2022-12-27 編程語(yǔ)言

golang中并沒(méi)有像java一樣提供類(lèi)似yyyy-MM-dd HH:mm:ss格式的操作,而是將其定義為golang的誕生時(shí)間:

2006-01-02 15:04:05 -0700 MST

注意這在golang的日期格式化里不是一個(gè)具體日期,而是格式,這樣如果我們需要格式化日期,可以如下操作

timeNow := time.Now()
fmt.Println("yyyy-MM-dd HH:mm:ss" ,timeNow.Format("2006-01-02 15:04:05"))
// 打印: yyyy-MM-dd HH:mm:ss: 2022-05-11 14:24:19

接下來(lái)說(shuō)下Time中的幾個(gè)方法:

Time.Unix() 獲取時(shí)間秒數(shù),返回的是unix時(shí)間秒

fmt.Println("from 1970-01-01 to now seconds: ",int32(time.Now().Unix()))

Time.Date() 返回年月日:

year,month,day := timeNow.Date()
fmt.Println(year,month,day)
// 注意打印的是: 2022 May 11

Time.AddDate 時(shí)間增減:

timeLast := timeNow.AddDate(0,0,-1)
fmt.Println(timeLast.Format("2006-01-02 15:04:05"))

Time.Add 增加指定的時(shí)間,可以精確到納秒

time2 := timeNow.Add(time.Duration(2000*time.Millisecond))
fmt.Println(time2.Format("2006-01-02 15:04:05"))

Time.After 是否在指定時(shí)間之后,如果是返回true Time.Before 是否在指定時(shí)間之前,如果是返回true time.Parse 按照指定格式將字符串轉(zhuǎn)換為日期:

time2,err := time.Parse("2006-01-02 15:04:05","2022-05-11 15:04:05")
if err != nil {
	fmt.Println(err)
}
fmt.Println(time2.Format("2006-01-02 15:04:05"))

補(bǔ)充:go語(yǔ)言時(shí)間和日期的轉(zhuǎn)化

go 語(yǔ)言中使用time.Time表示時(shí)間。我們可以通過(guò)time.Now函數(shù)獲取當(dāng)前的時(shí)間對(duì)象,然后從時(shí)間對(duì)象中可以獲取到年、月、日、時(shí)、分、秒等信息。

package main

import (
?? ?"fmt"
?? ?"time"
)

func main() {
?? ?t := time.Now() // 獲取當(dāng)前時(shí)間
?? ?fmt.Printf("當(dāng)前時(shí)間:%v\n", t)
?? ?fmt.Println("年", t.Year())
?? ?fmt.Println("月", t.Month())
?? ?fmt.Println("日", t.Day())
?? ?fmt.Println("時(shí)", t.Hour())
?? ?fmt.Println("分", t.Minute())
?? ?fmt.Println("秒", t.Second())
}

輸出

當(dāng)前時(shí)間:2022-05-19 21:38:39.7367663 +0800 CST m=+0.001805001
年 2022
月 May?
日 19 ?
時(shí) 21 ?
分 38 ?

time 包中定義的時(shí)間間隔類(lèi)型的常量如下:

const (
? ? Nanosecond ?Duration = 1
? ? Microsecond ? ? ? ? ?= 1000 * Nanosecond
? ? Millisecond ? ? ? ? ?= 1000 * Microsecond
? ? Second ? ? ? ? ? ? ? = 1000 * Millisecond
? ? Minute ? ? ? ? ? ? ? = 60 * Second
? ? Hour ? ? ? ? ? ? ? ? = 60 * Minute
)

例如:time.Hour表示1小時(shí),time.Second表示1秒。

總結(jié)

原文鏈接:https://blog.csdn.net/LeoHan163/article/details/124710250

欄目分類(lèi)
最近更新