SoFunction
Updated on 2025-03-03

Common methods for Go time operation (recommended!)

1. time package

1.1. Time Type

There are two types of time in Go:

  • : There are two common ways to represent the type of time:
    • (): Get the current time
    • (): Create time based on the specified year, month, day, hour, minute, second, nanosecond, etc.
  • : Represents the time elapsed between two time points, in nanoseconds

1.2. Time stamp

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.

1.3. Time interval

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

1.4. Time operation

There are two main types of time operations in Go:

  • Get time:()、()
  • Format time:()、()

2. Get time

2.1. Get the current time

In Go language, the current time is obtained through the () function and returns a local time of type.

func Now() Time
package main

import (
    "fmt"
    "time"
)

func main() {
    now := () // Get the current time    ("current time:%v\n", now)
}

2.2. Get the specified time

The () function can obtain the specified time, and its parameters are: year, month, day, hour, minute, second, nanosecond, time zone.

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
package main

import (
    "fmt"
    "time"
)

func main() {
    // Get the specified time    date := (2020, 1, 1, 0, 0, 0, 0, )
    ("date:%v\n", date)
}

3. Format time

3.1. Time type to string

In Go language, time can be formatted through the Format() function of type. The first parameter of the function is the formatted template. The time in the template must be 2006-01-02 15:04:05. This time is fixed, otherwise an error will occur. The second parameter is the time to be formatted.

func (t Time) Format(layout string) string
package main

import (
    "fmt"
    "time"
)

func main() {
    now := () // Get the current time    // The formatted template is Go's birth date January 2, 2006 at 15:04 Mon Jan    (("2006-01-02 15:04:05.000 Mon Jan"))
    (("2006/01/02 15:04"))
    (("15:04 2006/01/02"))
}

3.2. String to time type

In Go language, strings can be parsed through the () function to generate the corresponding type time.

func Parse(layout, value string) (Time, error)
package main

import (
    "fmt"
    "time"
)

func main() {
    // Loading time zone    loc, _ := ("Asia/Shanghai")
    // Parses string time according to the specified time zone and the specified format    timeObj, err := ("2006/01/02 15:04:05", "2020/01/01 00:00:00", loc)
    if err != nil {
        ("parse time failed, err:%v\n", err)
        return
    }
    (timeObj)
}

4. Time constant

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

5. Time operation

5.1. Get the 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.

func (t Time) Unix() int64
package main

import (
    "fmt"
    "time"
)

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

5.2. Time interval

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

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

import (
    "fmt"
    "time"
)

func main() {
    now := ()
    // The program execution will be paused for 2 seconds after it is executed here    (2 * )
    ("2 seconds later")
    // Two times subtract    ("passed %v\n", (now))
}

5.3. Timer

Type represents a single time event. When the timer expires, the current time is sent to C unless the timer is created by the AfterFunc function. Therefore, if the program holds a unique reference to the timer, when the timer fires, it is released and the timer stops.

func AfterFunc(d Duration, f func()) *Timer
package main

import (
    "fmt"
    "time"
)

func main() {
    timer := () // Define a 1-second interval timer    for t := range timer {
        (t) // Execute once in 1 second    }
}

5.4. Timer

Type represents a time event triggered by an interval, which will fire multiple times at an interval (for example, 1 second, 1 minute, etc.), sending an event to a channel.

func Tick(d Duration) *Ticker
package main

import (
    "fmt"
    "time"
)

func main() {
    ticker := () // Define a 1-second interval timer    for t := range  {
        (t) // Execute once in 1 second    }
}

6. Time zone

In Go, time zone information is loaded through the LoadLocation() function, and its parameters are the name of the time zone. We can obtain the time zone information through the LoadLocation(name string) (*Location, error) function in the time package. It returns a Location object, and then we can load the time zone information through the LoadLocation() function.

func LoadLocation(name string) (*Location, error)
package main

import (
    "fmt"
    "time"
)

func main() {
    // Loading time zone    loc, err := ("Asia/Shanghai")
    if err != nil {
        ("load location failed, err:%v\n", err)
        return
    }
    // Parses string time according to the specified time zone and the specified format    timeObj, err := ("2006/01/02 15:04:05", "2020/01/01 00:00:00", loc)
    if err != nil {
        ("parse time failed, err:%v\n", err)
        return
    }
    (timeObj)
}

7. Time zone conversion

func (t Time) In(loc *Location) Time
package main

import (
    "fmt"
    "time"
)

func main() {
    // Loading time zone    loc, _ := ("Asia/Shanghai")
    // Parses string time according to the specified time zone and the specified format    timeObj, err := ("2006/01/02 15:04:05", "2020/01/01 00:00:00", loc)
    if err != nil {
        ("parse time failed, err:%v\n", err)
        return
    }
    (timeObj)
    // Parse string time according to the time zone and format of East Eighth District    timeObj, err = ("2006/01/02 15:04:05", "2020/01/01 00:00:00")
    if err != nil {
        ("parse time failed, err:%v\n", err)
        return
    }
    (timeObj)
    // Convert timeObj to the specified time zone    newTime := (loc)
    (newTime)
}

Summarize

This is the end of this article about the common methods of Go time operation. For more relevant Go time operation content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!