SoFunction
Updated on 2025-03-05

Detailed explanation of the usage of golang package time

During our programming process, we often use various business needs related to time. Let’s introduce some basic usages of time in golang. Let’s start with several types of time.

Time can be divided into time points and time periods, golang is no exception, and it provides the following two basic types.

  1. Time point (Time)
  2. Duration

In addition, golang also provides the following types to do some specific business

  1. Time zone (Location)
  2. Ticker
  3. Timer (timer)

We will introduce the use of time packages in the above order.

Time point (Time)

All the time-related businesses we use are extended based on points, and two points form a time period, and most applications also revolve around these points and surfaces to perform logical processing.

initialization

go provides the following initialization methods for different parameter types

// func Now() Time
 (())

 // func Parse(layout, value string) (Time, error)
 ("2016-01-02 15:04:05", "2018-04-23 12:24:51")

 // func ParseInLocation(layout, value string, loc *Location) (Time, error) (Parse can be used directly when layout has time zone) ("2006-01-02 15:04:05", "2017-05-11 14:06:06", )

 // func Unix(sec int64, nsec int64) Time
 (1e9, 0)

 // func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
 (2018, 1, 2, 15, 30, 10, 0, )

 // func (t Time) In(loc *Location) Time The time in the current time corresponds to the specified time zone loc, _ := ("America/Los_Angeles")
 (().In(loc))

 // func (t Time) Local() Time

After obtaining the time point, in order to meet the business and design, it needs to be converted into the format we need, which is the so-called time formatting.

format

to string

Format as strings we need to use the method to convert to the format we want

(().Format("2006-01-02 15:04:05")) // 2018-04-24 10:11:20
 (().Format())  // Tue Apr 24 09:59:02 CST 2018

The Format function can specify the format you want to use, and the time package also gives some commonly used formats.

const (
 ANSIC = "Mon Jan _2 15:04:05 2006"
 UnixDate = "Mon Jan _2 15:04:05 MST 2006"
 RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
 RFC822 = "02 Jan 06 15:04 MST"
 RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
 RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
 RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
 RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
 RFC3339 = "2006-01-02T15:04:05Z07:00"
 RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
 Kitchen = "3:04PM"
 // Handy time stamps.
 Stamp = "Jan _2 15:04:05"
 StampMilli = "Jan _2 15:04:05.000"
 StampMicro = "Jan _2 15:04:05.000000"
 StampNano = "Jan _2 15:04:05.000000000"
)

Note: The specific time format specified in galang is "2006-01-02 15:04:05 -0700 MST". For the convenience of memory, the American time format, month, hour, minute, second, year, plus time zone, is arranged in sequence 01/02 03:04:05PM '06 -0700. You need to pay attention when you first use it.

to time stamp

func (t Time) Unix() int64
 func (t Time) UnixNano() int64

 (().Unix())

 // Get the time stamp of the specified date dt, _ := ("2016-01-02 15:04:05", "2018-04-23 12:24:51")
 (())

 ((2018, 1,2,15,30,10,0, ).Unix())

other

The time package also provides some commonly used methods, which basically covers most businesses. I won’t explain them one by one by one by one by one by one by one.

func (t Time) Date() (year int, month Month, day int)
 func (t Time) Clock() (hour, min, sec int)
 func (t Time) Year() int
 func (t Time) Month() Month
 func (t Time) Day() int
 func (t Time) Hour() int
 func (t Time) Minute() int
 func (t Time) Second() int
 func (t Time) Nanosecond() int
 func (t Time) YearDay() int
 func (t Time) Weekday() Weekday
 func (t Time) ISOWeek() (year, week int)
 func (t Time) IsZero() bool
 func (t Time) Local() Time
 func (t Time) Location() *Location
 func (t Time) Zone() (name string, offset int)
 func (t Time) Unix() int64

Duration

After introducing the time point, let’s introduce the time period, namely the Duartion type, which is also a very commonly used type in our business.

// func ParseDuration(s string) (Duration, error)
 tp, _ := ("1.5s")
 ((1000), (), ())

 func (d Duration) Hours() float64
 func (d Duration) Minutes() float64
 func (d Duration) Seconds() float64
 func (d Duration) Nanoseconds() int64
 func (d Duration) Round(m Duration) Duration  // Rounding func (d Duration) Truncate(m Duration) Duration // Round down

Time zone (Location)

Let's introduce the functions related to the time zone

// Default UTC loc, err := ("") 
 // The time zone set by the server is generally CST loc, err := ("Local")
 // PDT, Los Angeles, USA loc, err := ("America/Los_Angeles")

 // Get the time point in the specified time zone local, _ := ("America/Los_Angeles")
 ((2018,1,1,12,0,0,0, local))

All time zones can be seen under the $GOROOT/lib/time/ file.

Time operation

Okay, we have introduced the basic types. Now we start time calculation related functions, which are also widely used in daily business.

// func Sleep(d Duration) How long does it take to sleep? It is in a blocking state during sleep, and subsequent programs cannot be executed ((10) * )

 // func After(d Duration) <-chan Time Non-blocking, can be used for delays ((10) * )

 // func Since(t Time) Duration The interval between two time points start := ()
 ((start)) // is equivalent to Now().Sub(t), which can be used to calculate the consumption time of a business
 func Until(t Time) Duration // The interval between (Now()), t and the current time is equivalent to
 // func (t Time) Add(d Duration) Time
 (((10) * )) // add
 func (t Time) Sub(u Time) Duration   // reduce
 // func (t Time) AddDate(years int, months int, days int) Time
 ((1, 1, 1))

 // func (t Time) Before(u Time) bool
 // func (t Time) After(u Time) bool
 // func (t Time) Equal(u Time) bool Try to use the Equal function when comparing time points

We have roughly introduced most functions involving time points and time periods. Next, we will use some usage scenarios to make some demonstrations.

Use scenarios

Date time difference

dt1 := (2018, 1, 10, 0, 0, 1, 100, )
 dt2 := (2018, 1, 9, 23, 59, 22, 100, )
 // Don't pay attention to the time zone, go will be converted into a timestamp for calculation ((dt2))

Before and after operations based on the current time

now := ()

 // One day after one year and one month ((1,1,1))
 // After a while (((10)*))

 // Calculate the number of days between two time points dt1 = ((), (), (), 0, 0, 0, 0, )
 dt2 = ((), (), (), 0, 0, 0, 0, )
 (int(((dt2).Hours() / 24)))

Time zone conversion

// Used to represent the current server time zone // Customize regional time secondsEastOfUTC := int((8 * ).Seconds())
 beijing := ("Beijing Time", secondsEastOfUTC)
 ((2018,1,2,0,0,0,0, beijing)) // 2018-01-02 00:00:00 +0800 Beijing Time 

 // The current time is converted to the specified time zone (().In(beijing))

 // Convert the specified time to the corresponding time zone dt, err := ("2006-01-02 15:04:05", "2017-05-11 14:06:06", )

 // The current time is in the zero time zone, year, month, day, hour, minute, second time zone year, mon, day := ().UTC().Date() // 2018 April 24 
 hour, min, sec := ().UTC().Clock() // 3 47 15
 zone, _ := ().UTC().Zone()  // UTC

Compare two time points

dt := (2018, 1, 10, 0, 0, 1, 100, )
 (().After(dt)) // true
 (().Before(dt)) // false

 // Whether it is equal. It is recommended to use the Equal function when determining whether two time points are equal. ((()))

Set execution time

Used in combination with select can be used to handle program timeout settings

select {
 case m := <- c:
  // do something
 case <- ((1)*):
  ("time out")
 }

Ticker Type

The Ticker type contains a channel. Sometimes we encounter business that executes every once in a while (such as setting heartbeat time, etc.), and we can use it to handle it. This is a repetitive process.

// Cannot cancel tick := (1 * )
 for _ = range tick {
  // do something
 }

 // Can be cancelled by calling ticker := (1 * )
 for _ = range tick {
  // do something
 }

Timer type

The Timer type is used to represent a separate event. When the set time expires, the current time is sent to the channel. We can create it in the following two ways.

func AfterFunc(d Duration, f func()) *Timer // Specify the specified function after a period of time func NewTimer(d Duration) *Timer 

Both functions above can use Reset. One thing to note is that when using Reset, you need to ensure that the channel is released before it can be called to prevent resource competition. It can be solved in the following ways.

if !() {
  <-
 }
 (d)

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.