go語言的碎片整理 time

2022-06-10 09:36:07 字數 2119 閱讀 3299

時間和日期是我們程式設計中經常用到的,本文主要介紹了go語言內建的time包的基本用法。

go語言中匯入包

單行匯入

import "time"

import "fmt"

多行匯入

import (

"fmt"

"time"

time包

time.time型別表示時間。

func main(){

now := time.now()

fmt.printf("current time is :%v\n",now)

year := now.year()

month := now.month()

day := now.day()

hour := now.hour()

minute:= now.minute()

second := now.second()

fmt.printf("%d-%02d-%02d %02d:%02d:%02d\n",year,month,day,hour,minute,second)

時間戳時間戳是自2023年1月1日(08:00:00gmt)至當前時間的總毫秒數。它也被為unix時間戳。

func timestampdemo() {

now := time.now() //獲取當前時間

timestamp1 := now.unix() //時間戳

timestamp2 := now.unixnano() //納秒時間戳

fmt.printf("current timestamp1:%v\n", timestamp1)

fmt.printf("current timestamp2:%v\n", timestamp2)

使用time.unix()函式將時間戳轉為時間格式。

func timestampdemo2(timestamp int64) {

timeobj := time.unix(timestamp, 0) //將時間戳轉為時間格式

fmt.println(timeobj)

year := timeobj.year() //年

month := timeobj.month() //月

day := timeobj.day() //日

hour := timeobj.hour() //小時

minute := timeobj.minute() //分鐘

second := timeobj.second() //秒

fmt.printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)

定時器使用time.tick(時間間隔),來設定定時器。

func tickdemo(){

ticker := time.tick(time.second)

for i:=range ticker{

fmt.println(i)

時間間隔

duration型別代表兩個時間點之間經過的時間,以納秒為單位。可表示的最長時間段大約為290年。定義時間間隔常量如下:

const (無錫**醫院哪家好

nanosecond duration =1

microsecond =1000*nanosecond

millisecond =1000*microsecond

second =1000*millisecond

minute =60*second

hour =60*minute

例如:time.duration 表示1納秒,time.second表示1秒。

時間加時間間隔

我們在日常的編碼過程中可能會遇到要求時間+時間間隔的需求,go語言的時間物件有提供add方法如下:

func (t time) add(d duration) time

func main(){

now := time.now()

later := now.add(time.hour)

fmt.println(later)

兩個時間相減

求兩個時間之間的差值:

func (t time) sub(u time) duration

Go 語言時間包time的使用

time.time型別表示時間。時間型別 func timedemo 字串型別轉time s4 1999年10月19日 字串 t4,err time.parse 2006年01月02日 s4 if err nil fmt.println t4 時間戳是自1970年1月1日 08 00 00gmt 至...

go語言基礎 時間time包

time包下有很多跟時間有關係的方法,以前我們介紹的隨機數就是利用了time包下的乙個方法,接下來我再來介紹一些常用方法 日期和時間 now time,獲取當前的日期 date time,獲取指定的日期 time string,string time 格式化列印當前時間,要按照go語言特定的格式輸入...

Go語言基礎之time包

時間和日期是我們程式設計中經常會用到的,本文主要介紹了go語言內建的time包的基本用法。go語言中使用import關鍵字匯入包,包的名字使用雙引號 包裹起來。import time import fmt 匯入多個包時可以使用圓括號,包名的順序不影響匯入效果,例如 import fmt time 需...