Lixv

Lixv

Go time package details

The time package is the standard library in Go for handling time and dates. It provides many functions and types for representing and manipulating time, timers, durations, and time zones.

Brief Introduction#

Commonly used functions and types include:

Time representation and creation functions: Functions like Date(), Now(), Parse(), Unix(), etc., are used to create and obtain time objects, representing time in different ways.

Time formatting and parsing: The Format() and Parse() functions are used for converting between time objects and strings. By defining specific format templates, time can be formatted or parsed as needed.

Time calculation and comparison: Functions like Add(), AddDate(), Sub(), etc., are used for performing addition and subtraction operations on time, such as adding a certain duration, calculating the interval between two times, and supporting comparisons between times.

Duration handling: The Duration type is used to represent time intervals or durations, which can be expressed in nanoseconds, microseconds, milliseconds, seconds, minutes, and hours, and provides a series of methods for manipulating and converting durations.

Time zone handling: The Location type represents time zone information, allowing loading of system-defined or custom time zones. The LoadLocation() function can be used to load time zone information, and the In() and UTC() methods can convert time to a specific time zone or UTC time.

Timers: The Timer and Ticker types are used for triggering events at specified intervals. Timer is used to trigger a single event after a specified time, while Ticker is used to trigger repeated events at fixed time intervals.

The time package also includes other functions for time manipulation and formatting, as well as types representing months and days of the week.

There are many contents under the time package, and I think learning through examples is better. Below, I will introduce examples of commonly used functions in the time package according to the types defined in the official Go documentation:

Functions#

func After(d Duration) <-chan Time 
func Sleep(d Duration)
func Tick(d Duration) <-chan Time
package main

import (
	"fmt"
	"time"
)

func main() {
	// The After function returns a channel that receives a time value after a specified duration
	select {
	case <-time.After(2 * time.Second):
		fmt.Println("After")
	}

	// The Sleep function pauses the program for a specified duration
	fmt.Println("Start")
	time.Sleep(2 * time.Second)
	fmt.Println("End")

	// The Tick function returns a channel that receives a time value at specified intervals
	ticker := time.Tick(1 * time.Second)
	for tick := range ticker {
		fmt.Println("Tick:", tick)
	}
}
# Output
After
Start
End
Tick: 2023-05-28 19:52:59.051953 +0800 CST m=+5.002580117
Tick: 2023-05-28 19:53:00.051654 +0800 CST m=+6.002592024
Tick: 2023-05-28 19:53:01.050407 +0800 CST m=+7.001636794
Tick: 2023-05-28 19:53:02.050139 +0800 CST m=+8.001642844
...

Duration#

Duration represents a period of time.

func ParseDuration(s string) (Duration, error)
func Since(t Time) Duration
func Until(t Time) Duration
func (d Duration) Abs() Duration
func (d Duration) Hours() float64
func (d Duration) Microseconds() int64
func (d Duration) Milliseconds() int64
func (d Duration) Minutes() float64
func (d Duration) Nanoseconds() int64
func (d Duration) Round(m Duration) Duration
func (d Duration) Seconds() float64
func (d Duration) String() string
func (d Duration) Truncate(m Duration) Duration
package main

import (
	"fmt"
	"time"
)

func main() {
	// The ParseDuration function parses a string into a Duration type
	d, _ := time.ParseDuration("1h30m")
	fmt.Println("Parsed Duration:", d)

	// The Since function returns the duration between the current time and a specified time
	t := time.Date(2023, time.May, 7, 12, 0, 0, 0, time.UTC)
	duration := time.Since(t)
	fmt.Println("Time Since:", duration)

	// The Until function returns the duration between a specified time and the current time
	duration = time.Until(t)
	fmt.Println("Time Until:", duration)

	// Common methods of the Duration type
	duration = 2 * time.Hour + 30 * time.Minute
	fmt.Println("Hours:", duration.Hours())
	fmt.Println("Minutes:", duration.Minutes())
	fmt.Println("Seconds:", duration.Seconds())
	fmt.Println("Milliseconds:", duration.Milliseconds())
	fmt.Println("Microseconds:", duration.Microseconds())
	fmt.Println("Nanoseconds:", duration.Nanoseconds())

	// Formatting output of the Duration type
	fmt.Println("Duration String:", duration.String())
}
# Return values
Parsed Duration: 1h30m0s
Time Since: 504h21m51.536756s
Time Until: -504h21m51.536761s
Hours: 2.5
Minutes: 150
Seconds: 9000
Milliseconds: 9000000
Microseconds: 9000000000
Nanoseconds: 9000000000000
Duration String: 2h30m0s

Location#

The Location type represents a geographical location, and we can set our time location using LoadLocation.

type Location:

func FixedZone(name string, offset int) *Location
func LoadLocation(name string) (*Location, error)
func LoadLocationFromTZData(name string, data []byte) (*Location, error)
func (l *Location) String() string
package main

import (
	"fmt"
	"time"
)

func main() {
	// The FixedZone function creates a time zone with a fixed offset
	zone := time.FixedZone("CST", int(8*time.Hour.Seconds()))
	fmt.Println("Fixed Zone:", zone)

	// The LoadLocation function loads a time zone by its name
	shanghai, err := time.LoadLocation("Asia/Shanghai") // UTC+08:00
	if err != nil {
		fmt.Println("Failed to load Asia/Shanghai location:", err)
		return
	}
	timeInShanghai := time.Date(2023, 5, 28, 20, 0, 0, 0, shanghai)
	fmt.Println("Time in Shanghai:", timeInShanghai)

	newYork, err := time.LoadLocation("America/New_York")
	if err != nil {
		fmt.Println("Failed to load America/New_York location:", err)
		return
	}
	timeInNewYork := timeInShanghai.In(newYork)
	fmt.Println("Time in New York:", timeInNewYork)

	timesAreEqual := timeInShanghai.Equal(timeInNewYork)
	fmt.Println(timesAreEqual)
}

Now, timeInShanghai has been converted to the New York time zone, so it represents the same point in time as timeInNewYork, and the Equal method will return true.

Month#

The Month type

func (m Month) String() string
package main

import (
	"fmt"
	"time"
)

func main() {
	// The String method returns the string representation of the Month type
	month := time.May
	fmt.Println("Month String:", month.String())
}

ParseError#

func (e *ParseError) Error() string
package main

import (
	"fmt"
	"time"
)

func main() {
	// The Parse function may return a ParseError type error when parsing a time string
	_, err := time.Parse("2006-01-02", "invalid")
	if err != nil {
		parseError := err.(*time.ParseError)
		fmt.Println("Parse Error:", parseError.Error())
	}
}

Ticker#

The Ticker is primarily a timer.

func NewTicker(d Duration) *Ticker
func (t *Ticker) Reset(d Duration)
func (t *Ticker) Stop()
package main

import (
	"fmt"
	"time"
)

func main() {
	// The NewTicker function creates a Ticker object that triggers at specified intervals
	ticker := time.NewTicker(1 * time.Second)

	go func() {
		for tick := range ticker.C {
			fmt.Println("Tick:", tick)
		}
	}()

	// Stop the Ticker
	time.Sleep(5 * time.Second)
	ticker.Stop()
	fmt.Println("Ticker Stopped")
}

Time Type#

The Time type is the most commonly used type in the time package.

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
func Now() Time
func Parse(layout, value string) (Time, error)
func ParseInLocation(layout, value string, loc *Location) (Time, error)
func Unix(sec int64, nsec int64) Time
func UnixMicro(usec int64) Time
func UnixMilli(msec int64) Time
func (t Time) Add(d Duration) Time
func (t Time) AddDate(years int, months int, days int) Time
func (t Time) After(u Time) bool
func (t Time) AppendFormat(b []byte, layout string) []byte
func (t Time) Before(u Time) bool
func (t Time) Clock() (hour, min, sec int)
func (t Time) Compare(u Time) int
func (t Time) Date() (year int, month Month, day int)
func (t Time) Day() int
func (t Time) Equal(u Time) bool
func (t Time) Format(layout string) string
func (t Time) GoString() string
func (t *Time) GobDecode(data []byte) error
func (t Time) GobEncode() ([]byte, error)
func (t Time) Hour() int
func (t Time) ISOWeek() (year, week int)
func (t Time) In(loc *Location) Time
func (t Time) IsDST() bool
func (t Time) IsZero() bool
func (t Time) Local() Time
func (t Time) Location() *Location
func (t Time) MarshalBinary() ([]byte, error)
func (t Time) MarshalJSON() ([]byte, error)
func (t Time) MarshalText() ([]byte, error)
func (t Time) Minute() int
func (t Time) Month() Month
func (t Time) Nanosecond() int
func (t Time) Round(d Duration) Time
func (t Time) Second() int
func (t Time) String() string
func (t Time) Sub(u Time) Duration
func (t Time) Truncate(d Duration) Time
func (t Time) UTC() Time
func (t Time) Unix() int64
func (t Time) UnixMicro() int64
func (t Time) UnixMilli() int64
func (t Time) UnixNano() int64
func (t *Time) UnmarshalBinary(data []byte) error
func (t *Time) UnmarshalJSON(data []byte) error
func (t *Time) UnmarshalText(data []byte) error
func (t Time) Weekday() Weekday
func (t Time) Year() int
func (t Time) YearDay() int
func (t Time) Zone() (name string, offset int)
func (t Time) ZoneBounds() (start, end Time)
package main

import (
	"fmt"
	"time"
)

func main() {
	// The Date function creates a Time object based on the specified year, month, day, hour, minute, second, nanosecond, and location
	date := time.Date(2023, time.May, 7, 12, 0, 0, 0, time.UTC)
	fmt.Println("Date:", date)

	// The Now function returns the current time as a Time object
	now := time.Now()
	fmt.Println("Now:", now)

	// The Parse function parses a specified time string into a Time object
	// The first parameter must be 2006-01-02 15:04:05
	parsedTime, _ := time.Parse("2006-01-02 15:04:05", "2023-05-07 12:00:00")
	fmt.Println("Parsed Time:", parsedTime)

	// The Unix function creates a Time object based on a Unix timestamp
	unixTime := time.Unix(1670140800, 0)
	fmt.Println("Unix Time:", unixTime)

	// Common methods of the Time type
	fmt.Println("Year:", now.Year())
	fmt.Println("Month:", now.Month())
	fmt.Println("Day:", now.Day())
	fmt.Println("Hour:", now.Hour())
	fmt.Println("Minute:", now.Minute())
	fmt.Println("Second:", now.Second())
	fmt.Println("Nanosecond:", now.Nanosecond())
	fmt.Println("Weekday:", now.Weekday())

	// Formatting output of the Time object's string representation
	fmt.Println("Formatted Time:", now.Format("2006-01-02 15:04:05"))

	// Time comparison
	otherTime := time.Date(2023, time.May, 7, 10, 0, 0, 0, time.UTC)
	fmt.Println("Before:", now.Before(otherTime))
	fmt.Println("After:", now.After(otherTime))
	fmt.Println("Equal:", now.Equal(otherTime))

	// Time calculation
	afterTime := now.Add(2 * time.Hour)
	fmt.Println("After 2 Hours:", afterTime)

	addedDate := now.AddDate(1, 0, 0) // Add one year
	fmt.Println("Added Date:", addedDate)

	// Time zone related operations
	loc, _ := time.LoadLocation("America/New_York")
	localTime := now.In(loc)
	fmt.Println("Local Time:", localTime)

	utcTime := localTime.UTC()
	fmt.Println("UTC Time:", utcTime)

	// Timestamps
	unix := now.Unix()
	unixMicro := now.UnixMicro()
	unixMilli := now.UnixMilli()
	unixNano := now.UnixNano()
	fmt.Println("Unix:", unix)
	fmt.Println("Unix Micro:", unixMicro)
	fmt.Println("Unix Milli:", unixMilli)
	fmt.Println("Unix Nano:", unixNano)
}
// Output
Date: 2023-05-07 12:00:00 +0000 UTC
Now: 2023-05-28 20:37:21.055316 +0800 CST m=+0.000293065
Parsed Time: 2023-05-07 12:00:00 +0000 UTC
Unix Time: 2022-12-04 16:00:00 +0800 CST
Year: 2023
Month: May
Day: 28
Hour: 20
Minute: 37
Second: 21
Nanosecond: 55316000
Weekday: Sunday
Formatted Time: 2023-05-28 20:37:21
Before: false
After: true
Equal: false
After 2 Hours: 2023-05-28 22:37:21.055316 +0800 CST m=+7200.000293065
Added Date: 2024-05-28 20:37:21.055316 +0800 CST
Local Time: 2023-05-28 08:37:21.055316 -0400 EDT
UTC Time: 2023-05-28 12:37:21.055316 +0000 UTC
Unix: 1685277441
Unix Micro: 1685277441055316
Unix Milli: 1685277441055
Unix Nano: 1685277441055316000

The above are examples of some commonly used functions and types in the time package, which you can refer to and use as needed.

Summary#

Common operations of the time package summarized:

  • Creating and representing time: Use functions like Date(), Now(), Parse(), Unix(), etc., to create and obtain time objects.
  • Formatting and parsing time: Use Format() and Parse() functions to convert between time objects and strings.
  • Time calculation and comparison: Use functions like Add(), AddDate(), Sub(), etc., to perform addition and subtraction operations on time and compare the order of times.
  • Duration handling: Use the Duration type to represent time intervals and perform conversions and operations on time units.
  • Time zone handling: Use the Location type to represent time zones, load predefined time zone information, and convert time to specific time zones.
  • Timers and tickers: Use Timer and Ticker types to trigger events at specified intervals.

The above is a brief summary of the time package, which is an important tool for handling time and date-related operations, and you can use its functions and types according to your actual needs.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.