SoFunction
Updated on 2025-03-05

An article will help you understand the Go language standard library Time

Preface

During the programming process, we often use various requirements related to time and date. Here are some basic uses of time in Go.

Time Type

Type indicates time. Can be passed()The function obtains the current time object, and then obtains the time object's year, month, day, time, minute, and second information.

The sample code is as follows:

func main() {
  now := () //Get the current time  ("Current time:%v\n", now)
  //Current time: 2021-12-26 09:38:42.334358833 +0000 UTC m=+0.000056108	
  year := ()     //Year  month := ()   //moon  day := ()       //day  hour := ()     //Hour  minute := () //minute  second := () //Second  ("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
  ("%T,%T,%T,%T,%T,%T,%T\n", now, year, month, day, hour, minute, second)
  //,int,,int,int,int,int
}

Timestamp

The timestamp is the total number of milliseconds from January 1, 1970 (08:00:00GMT) to the current time. It is also called Unix Timestamp. In GoLang, the operation of obtaining timestamps is as follows:

func main() {
  now := ()            //Get the current time  timestamp1 := ()     //Time stamp  timestamp2 := () //Nanosec timestamp  ("current timestamp1:%v\n", timestamp1)
  ("current timestamp2:%v\n", timestamp2)
}

Can be passedto convert the timestamp directly into the current time format.

func main() {
  timestamp := ().Unix()
  timeObj := (timestamp, 0) //Convert timestamp to time format  (timeObj) //2021-12-26 09:47:39 +0000 UTC
  year := ()     //Year  month := ()   //moon  day := ()       //day  hour := ()     //Hour  minute := () //minute  second := () //Second  ("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second) //2021-12-26 09:47:39
}

Time interval

is a type defined by the time package, which represents the time elapsed between two time points, in nanoseconds. It represents a period of time interval, and the maximum time period that can be represented is about 290 years.

The constants of the time interval type defined in the time package are as follows:

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

For example: means 1 nanosecond, 1 second.

Operation time

Add

For time + time interval requirements, we can useAddThe method is as follows:

func (t Time) Add(d Duration) Time

func main() {
	now := ()
	(now)
	
	h := (1)
	m := (2)
	s := (3)
	// The current time is added to 1 hour, 2 minutes and 3 seconds	later := (*h + *m + *s) 
	(later)
}

Note that the year, month, day cannot be added here, but only time, minute, and second, that is, constants in the time interval type.

Sub

Find the difference between two times:

func (t Time) Sub(u Time) Duration

Returns a time period t-u. If the result exceeds the maximum/min value that Duration can represent, the maximum/min value will be returned. To get the point in time t-d (d is Duration), you can use (-d).

func main() {
  now := ()
  (now)
	
  targetTime := ()
  // The target time is 1h0m0s different from this time  ((now)) //1h0m0s
	
  before := (*-1) // The time after the current time is reduced by 1 hour  (before)
}

Equal

func (t Time) Equal(u Time) bool

To determine whether the two times are the same, the influence of the time zone will be taken into account, so the time standard for different time zones can also be compared correctly. Unlike using t==u, this method also compares location and time zone information.

Before

func (t Time) Before(u Time) bool

If the time point represented by t is before u, return true; otherwise, return false.

After

func (t Time) After(u Time) bool

If the time point represented by t is after u, return true; otherwise, return false.

Timer

Use (time interval) to set the timer.

func main() {
  ticker := () //Define a 1-second interval timer  for i := range ticker {
    (i)//Tasks that will be executed every second  }
}

Time formatting

There is a method for the time typeFormatFor formatting, it should be noted that formatting time templates are not common in Go language.Y-m-d H:M:SInstead, it was used to use Go. It was born at 15:04 on January 2, 2006 (the memory formula is 2006 1 2 3 4).

func main() {
    now := ()
    // The formatted template is Go's birth date January 2, 2006 at 15:04 Mon Jan    // 24-hour system    (("2006-01-02 15:04:05.000 Mon Jan"))
    // 12-hour system    (("2006-01-02 03:04:05.000 PM Mon Jan"))
    (("2006/01/02 15:04"))
    (("15:04 2006/01/02"))
    (("2006/01/02"))
}

Time to parse string format

now := ()
(now)
// Loading time zoneloc, err := ("Asia/Shanghai")
if err != nil {
    (err)
    return
}
// Parse string time according to the specified time zone and the specified formattimeObj, err := ("2006/01/02 15:04:05", "2021/12/27 18:48:44", loc)
if err != nil {
    (err)
    return
}
(timeObj)
((now))

Summarize

This is all about this article about Go Language Standard Library Time. For more relevant Go Language Standard Library Time content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!