Timing operations are unavoidable in program development, so here are some common operations in Go.

Duration

The lowest data structure of time in Go is Duration. Based on Duration, we define the following concepts:

Const (Nanosecond Duration = 1 // Nanosecond, ns Microsecond = 1000 * Nanosecond, Duration (us Millisecond = 1000 * Microsecond Millisecond) Hour = 60 * Minute Hour = 60 * Minute Hour = 60 * MinuteCopy the code

So how can Duration be manipulated?

  • time.Duration
seconds := 10
time.Duration(seconds)*time.Second // Returns the Duration structure
Copy the code
  • time.ParseDuration ParseDutationIt is mainly used to parse strings, and can be avoided if strings are usedtime.DurationInconvenient time period.
hours, _ := time.ParseDuration("10h") // Create a 10-hour duration complex, _ := time.parseDuration ("1h10m10s"Duration micro, _ := time.parseDuration ()"1 (including s") // Generates 1 subtle durationCopy the code
  • time.Sub

How to calculate the time difference between two times, return the Duration structure? Pay attention to

start := time.Date(2000.1.1.0.0.0.0, time.UTC)
end := time.Date(2000.1.1.12.0.0.0, time.UTC)

difference := end.Sub(start)
fmt.Printf("difference = %v\n", difference)
Copy the code
  • time.Since

Time.since is equivalent to time.now ().sub (t) and is used to calculate the difference between the current time and some previous time.

  • time.Until

Time. Until is equivalent to t.sub (time.now ()), which is used to calculate the time difference between a later time and the current time.

So what exactly is Duration’s data structure? Duration is just a nickname for INT64, on which several methods are implemented, such as. Hours (), you can (), the Seconds (), etc.

type Duration int64
Copy the code

Location

In general, you don’t need to set Location, but if you do, where can you use it? The last parameter sets the time zone where the current time is located.

Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location)
Copy the code

How is time.Location initialized? Use time.loadLocation to load

location, err := time.LoadLocation("America/Los_Angeles")
timeInUTC := time.Date(2018.8.30.12.0.0.0, time.UTC) // time.UTC is the *Location structure
Copy the code

Time conversion with time zone,

T := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)"Go launched at %s\n", t.Local()) // t.Local converts local time, 2009-11-11 07:00:00 +0800 CST.Copy the code

What about the east 8th?

/ / method
l,_ := time.LoadLocation("Asia/Shanghai") 

// Define a name and calculate your own time zone +-12 * 3600
var cstZone = time.FixedZone("CST".8*3600)       / / east eight
fmt.Println(time.Now().In(cstZone).Format("The 01-02-2006 15:04:05"))
Copy the code

Why do I multiply by 3600? Counting from seconds, the next two lines get the Beijing time zone.

secondsEastOfUTC := int((8 * time.Hour).Seconds())
beijing := time.FixedZone("Beijing Time", secondsEastOfUTC) 
Copy the code

Ticker

type Ticker struct {
    C <-chan Time // channel sends messages at fixed intervals
}
Copy the code

It sends a signal at a fixed time, and how do you get that fixed time? The Duration object is received via NewTicker, and the following code demonstrates the ability to print 10 seconds per 1 second print.

ticker := time.NewTicker(time.Second)
defer ticker.Stop() [Important] Disable ticker
done := make(chan bool)
go func(a) {
    time.Sleep(10 * time.Second)
    done <- true} ()for {
    select {
    case <-done:
        fmt.Println("Done!")
        return
    case t := <-ticker.C:
        fmt.Println("Current time: ", t)
    }
}
Copy the code

Time

Time is the core object for manipulating Time.

  • Time. The Parse time. ParseInLocation
time.Parse(layout, string) // Gets the time represented by the specified string
time.ParseInLocation(layout, value string, loc *Location) // Add the time of the time zone
Copy the code

Today I encountered a problem in development. How many seconds do you calculate between two times?

todayEnd, _ := time.Parse(timeLayout, fmt.Sprintf("%s %s", time.Now().Format("2006-01-02"), "23:59:59"))
todayStart := time.Now()
validSeds := todayEnd.Sub(todayStart).Minutes()
fmt.Println("validSeds: ".int(validSeds)) 
Copy the code

Time. Now uses the local time zone. This code needs to be modified to the following form:

l, _ := time.LoadLocation("Asia/Shanghai")
todayEnd, _ := time.ParseInLocation(timeLayout, fmt.Sprintf("%s %s", time.Now().Format("2006-01-02"), "23:59:59"), l)
Copy the code
  • time.Unix, time.UnixNano

Computes the current timestamp

Time.unix () // time.unixnano () // milliseconds

  • time.Add

Add a Duration.

  • time.AddDate
play 

start := time.Date(2009.1.1.0.0.0.0, time.UTC)
oneDayLater := start.AddDate(0.0.1) // Add a day
oneMonthLater := start.AddDate(0.1.0) // Add a month
oneYearLater := start.AddDate(1.0.0) // Add a year
Copy the code

However, AddDate can be solved using Add+Duraion.

  • T.A fter, t.B efore

Compare the sequence of the two times

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

isYear3000BeforeYear2000 := year3000.Before(year2000) // false
isYear2000BeforeYear3000 := year2000.Before(year3000) // true
Copy the code
  • t.Date, t.Clock
Func (t Time) Clock() (hour, min, SEC int) func (t Time) Date() (year int, month month, day int) // Returns the Date of tCopy the code
  • T. format Time formatting display

  • T.n Changes the current time zone by copying

func (t Time) In(loc *Location) Time
Copy the code
  • t.IsZero

1 January 1, Year 1, 00:00:00 UTC

  • t.Local, t.UTC

Generate time in the local time zone and time in the 0 time zone.

  • t.Zone()

Returns the name of the current time zone and the offset 0 time zone by how many seconds

t := time.Date(2009, time.November, 10.23.0.0.0, time.Local)
name, offset := t.Zone()
fmt.Println(name, offset) // CST 28800(8*3600)
Copy the code

Timer

What is a Timer? It’s basically a channel

Type Timer struct {C <-chan Time}Copy the code

How do I initialize the Timer?

func NewTimer(d Duration) *Timer
Copy the code

Time is up, what function to execute?

func AfterFunc(d Duration, f func(a)) *Timer
Copy the code

If you want to stop timer halfway, how to do?

func (t *Timer) Stop(a) bool
Copy the code

To ensure closure?

if! t.Stop() { <-t.C }Copy the code

The Month, Weekday

The way the two wraps work is the same, with more methods mounted using nicknames, and more possibilities for variables.


// Month
type Month int
const (
    January Month = 1 + iota
    February
    March
    April
    May
    June
    July
    August
    September
    October
    November
    December
)
func (m Month) String(a) string{}

// Weekday 
type Weekday int 
const (
    Sunday Weekday = iota
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
)
func (d Weekday) String(a) string
Copy the code