当前位置:网站首页>[go] time package

[go] time package

2022-06-21 14:55:00 Cabbage that wants to become powerful


One 、time Package introduction

Time and date are often used in our development ,Go In language time The package provided. Time display and measurement Etc , This article introduces time Basic usage of a package .


Two 、 principle

Time generally includes Time value and The time zone , It can be downloaded from Go In language time Bag Source code See in :

type Time struct {
    
    // wall and ext encode the wall time seconds, wall time nanoseconds,
    // and optional monotonic clock reading in nanoseconds.
    //
    // From high to low bit position, wall encodes a 1-bit flag (hasMonotonic),
    // a 33-bit seconds field, and a 30-bit wall time nanoseconds field.
    // The nanoseconds field is in the range [0, 999999999].
    // If the hasMonotonic bit is 0, then the 33-bit field must be zero
    // and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext.
    // If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit
    // unsigned wall seconds since Jan 1 year 1885, and ext holds a
    // signed 64-bit monotonic clock reading, nanoseconds since process start.
    wall uint64
    ext  int64
    // loc specifies the Location that should be used to
    // determine the minute, hour, month, day, and year
    // that correspond to this Time.
    // The nil location means UTC.
    // All UTC times are represented with loc==nil, never loc==&utcLoc.
    loc *Location
}
  1. wall: Indicates the distance from 1 year 1 month 1 Japan 00:00:00UTC The number of seconds ;
  2. ext: Represents nanosecond ;
  3. loc: Represents the time zone , It mainly deals with offset , Different time zones , The corresponding time is different .

How to express time correctly ?

It is generally accepted that the most accurate calculation is to use “ Atomic oscillation period ” The calculated physical clock (Atomic Clock, Also known as atomic clock ), This is also defined as standard time (International Atomic Time).

And what we often see UTC(Universal Time Coordinated, World coordinated time ) It's using this Atomic Clock The correct time defined for the benchmark .UTC The standard time is in GMT(Greenwich Mean Time, GMT ) This time zone is dominant , So local time and UTC The time difference is the difference between local time and GMT Time difference .

UTC +  Time zone difference  =  Local time 

Beijing time is commonly used in China , And UTC The time relationship of is as follows :

UTC + 8  Hours  =  Beijing time. 

stay Go Linguistic time There are two time zone variables in the package , as follows :

time.UTC:UTC  Time 
time.Local: Local time 

meanwhile ,Go Language also provides LoadLocation Methods and FixedZone Method to get the time zone variable , as follows :

FixedZone(name string, offset int) *Location

among ,name Is the time zone name ,offset Is with the UTC Time difference before .

LoadLocation(name string) (*Location, error)

among ,name Is the name of the time zone .


3、 ... and 、 Time acquisition

1. Get the current time - time.Now()

We can go through time.Now() Function to get The current time object , Then get the current time information through the event object . The sample code is as follows :

package main

import ( 
	"fmt"
	"time"
)

func main() {
    
	now := time.Now() // Get the current time 
	fmt.Printf("current time:%v\n", now)
	
	year := now.Year()     // year 
	month := now.Month()   // month 
	day := now.Day()       // Japan 
	hour := now.Hour()     // Hours 
	minute := now.Minute() // minute 
	second := now.Second() // second 
	fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}

Output results :

current time:2022-02-22 11:03:59.8710199 +0800 CST m=+0.004087501
2022-02-22 11:03:59

On the time object , You can call Year() 、Month()、Day()、Hour()、Minute()、Second() And other methods to obtain the specific year 、 month 、 Japan 、 Hours 、 minute 、 Seconds, etc .

2. Get the timestamp - Unix()、UnixNano()

The time stamp is from 1970 year 1 month 1 Japan (08:00:00GMT) The total number of milliseconds to the current time , It's also called Unix Time stamp (UnixTimestamp).

The sample code for obtaining time stamp based on time object is as follows :

package main

import (
	"fmt"
	"time"
)

func main() {
    
	now := time.Now()            // Get the current time 
	timestamp1 := now.Unix()     // Time stamp 
	timestamp2 := now.UnixNano() // Nanosecond time stamp 
	fmt.Printf(" Now the timestamp :%v\n", timestamp1)
	fmt.Printf(" Now the nanosecond timestamp :%v\n", timestamp2)
}

Output results :

 Now the timestamp :1645499594
 Now the nanosecond timestamp :1645499594139315000

Be careful :
First pass time.Now() Get the current time object , Then call the timestamp method on the time object Unix() or UnixNano() To get the timestamp .

Use time.Unix() function Sure Convert timestamps to time format ( Time object ), The sample code is as follows :

package main

import (
	"fmt"
	"time"
)

func main() {
    
	now := time.Now()                  // Get the current time 
	timestamp := now.Unix()            // Time stamp 
	timeObj := time.Unix(timestamp, 0) // Convert timestamps to time format 
	fmt.Println(timeObj)
	
	year := timeObj.Year()     // year 
	month := timeObj.Month()   // month 
	day := timeObj.Day()       // Japan 
	hour := timeObj.Hour()     // Hours 
	minute := timeObj.Minute() // minute 
	second := timeObj.Second() // second 
	fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}

Output results :

2022-02-22 11:17:09 +0800 CST
2022-02-22 11:17:09

adopt time.Unix() Function will convert the timestamp to a time object , You can call other methods on the time object .

3. Get the current day of the week - Weekday()

time In bag Weekday Method It can return the day of the week corresponding to a certain time point , The sample code is as follows :

package main

import (
	"fmt"
	"time"
)

func main() {
    
	t := time.Now()                     // Get time object 
	fmt.Println(t.Weekday().String())   // Call... On the time object Weekday() Method 
}

Output results :

Tuesday

Four 、 Time operation function

1. Add

We may encounter a request for a certain time in the daily development process + Time interval and so on ,Go In language Add The method is as follows :

func (t Time) Add(d Duration) Time    // In time objects Time The method defined above Add, Return a time object 

Add The function can return Point in time t + The time interval d Value .
To get a point in time t - d(d by Duration), have access to t.Add(-d).

example : Ask for the time in an hour

package main

import (
	"fmt"
	"time"
)

func main() {
    
	now := time.Now()
	fmt.Println(now)

	later := now.Add(time.Hour) //  Current time plus 1 Hours later 
	fmt.Println(later)
}

Output results :

2022-02-22 11:28:38.3280421 +0800 CST m=+0.004958801
2022-02-22 12:28:38.3280421 +0800 CST m=+3600.004958801

2. Sub

Find the difference between two times :

func (t Time) Sub(u Time) Duration   // In time objects Time The method defined above Sub, Pass in a time object , Returns the time interval between two time objects Duration 

Return to a time period t - u Value . If the result exceeds Duration The maximum or minimum value that can be represented , The maximum or minimum value will be returned .

package main

import (
	"fmt"
	"time"
)

func main() {
    
	now := time.Now()
	fmt.Println(now)

	later := now.Add(time.Hour) //  Current time plus 1 Hours later 
	fmt.Println(later)

	d := later.Sub(now)
	fmt.Println(d)
}

Output results :

2022-02-22 11:34:28.383694 +0800 CST m=+0.004515101
2022-02-22 12:34:28.383694 +0800 CST m=+3600.004515101
1h0m0s

3. Equal

Determine if the two times are the same :

func (t Time) Equal(u Time) bool

Equal The function takes into account the time zone , Therefore, the standard time of different time zones can also be correctly compared ,Equal Method and Application t==u Different ,Equal Method also compares location and time zone information .

4. Before

Judge whether one time point is before another time point :

func (t Time) Before(u Time) bool

If t The representative's time is u Before , Then return to true , Otherwise return false .

5. After

Judge whether one time point is after another time point :

func (t Time) After(u Time) bool

If t The representative's time is u after , Then return to true , Otherwise return false .


5、 ... and 、 Timer

Use time.Tick( The time interval ) You can set the timer , A timer is essentially a channel (channel), The sample code is as follows :

package main

import (
	"fmt"
	"time"
)

func main() {
    
	ticker := time.Tick(time.Second) // Define a 1 Second interval timer ,Tick It's a cycle timer 
	tag := 0
	for i := range ticker {
       // Traverse timer  ticker 
		tag++
		fmt.Println(i) // Tasks that are performed every second 
		if tag == 10 {
    
			break
		}
	}
}

Output results :

2022-02-22 11:40:04.0331504 +0800 CST m=+1.005876601
2022-02-22 11:40:05.0394583 +0800 CST m=+2.012184501
2022-02-22 11:40:06.0464968 +0800 CST m=+3.019223001
2022-02-22 11:40:07.0375901 +0800 CST m=+4.010316301
2022-02-22 11:40:08.0451185 +0800 CST m=+5.017844701
2022-02-22 11:40:09.0343462 +0800 CST m=+6.007072401
2022-02-22 11:40:10.0455835 +0800 CST m=+7.018309701
2022-02-22 11:40:11.0379969 +0800 CST m=+8.010723101
2022-02-22 11:40:12.0464238 +0800 CST m=+9.019150001
2022-02-22 11:40:13.0389829 +0800 CST m=+10.011709101

so , Timer ticker Equivalent to a channel (channel), It happens every second , A time object is generated .( This channel puts a time object every second )


6、 ... and 、 Time format


7、 ... and 、


Reference link

  1. Go Language time package : Time and date
原网站

版权声明
本文为[Cabbage that wants to become powerful]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221334003024.html