Time in Go

Go: Time

Go provides a built-in package called time for working with time and dates. The time package provides functionality for measuring time durations, formatting time and dates, parsing strings into time values, and performing various time-related calculations.

Here are a few examples of how to use the time package:

Getting the current time in Go

To get the current time in Go, you can use the time.Now() function, which returns a time.Time value representing the current local time.


package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    fmt.Println(now) // Output: 2023-03-14 13:42:18.087111 +0800 CST m=+0.000191548
}

### Formatting time and dates in Go

To format a time.Time value as a string, you can use the Time.Format() method, which takes a format string and returns a formatted string representation of the time.

```go

    package main

    import (
        "fmt"
        "time"
    )

    func main() {
        now := time.Now()
        fmt.Println(now.Format("2006-01-02 15:04:05")) // Output: 2023-03-14 13:42:18
    }

In the format string, the following placeholders can be used to represent various parts of the time value:

  • 2006: the year
  • 01: the numeric month (with leading zero)
  • 02: the day of the month (with leading zero)
  • 15: the hour (in 24-hour format)
  • 04: the minute
  • 05: the second
  • PM: the time period (AM or PM)
  • MST: the time zone abbreviation (e.g. CST)

Parsing strings into time values in Go

To parse a string into a time.Time value, you can use the time.Parse() function, which takes a format string and a string value and returns a time.Time value representing the parsed time.


    package main

    import (
        "fmt"
        "time"
    )

    func main() {
        dateStr := "2023-03-14 13:42:18"
        date, err := time.Parse("2006-01-02 15:04:05", dateStr)
        if err != nil {
            panic(err)
        }
        fmt.Println(date) // Output: 2023-03-14 13:42:18 +0000 UTC
    }

Working with time durations in Go

To represent a duration of time in Go, you can use the time.Duration type, which represents a length of time in nanoseconds. You can create a time.Duration value by calling the time.Duration() function and passing in a number of nanoseconds.


    package main

    import (
        "fmt"
        "time"
    )

    func main() {
        duration := time.Duration(5) * time.Minute
        fmt.Println(duration) // Output: 5m0s
    }
  • You can also perform arithmetic operations on time.Duration values, such as adding or subtracting durations or multiplying by a scalar value.

    package main

    import (
        "fmt"
        "time"
    )

    func main() {
        duration := time.Duration(5) * time.Minute
        duration += 30 * time.Second
        fmt.Println(duration) // Output: 5m30s

        duration *= 2
        fmt.Println(duration) // Output: 11m0s

Previous Article