The golang time package is explained in detail
- 2020-07-21 08:21:16
- OfStack
Time related business requirements are often used in our programming process. Here are some basic USES of time in golang, starting with several type versions of time.
Time can be divided into time points and time periods, and golang is no exception, providing the following two basic types
- Point in time (Time)
- Time period (Duration)
ChuCiZhiWai golang 也提供了以下类型,做1些特定的业务
- time zone (Location)
- Ticker
- Timer(timer)
We will cover the time package in the above order.
Time points (Time)
All of the time-related businesses we use are extended based on points, which constitute a period of time, and most applications do logical processing around these points and surfaces.
Initialize the
go provides the following initialization for different parameter types
// func Now() Time
fmt.Println(time.Now())
// func Parse(layout, value string) (Time, error)
time.Parse("2016-01-02 15:04:05", "2018-04-23 12:24:51")
// func ParseInLocation(layout, value string, loc *Location) (Time, error) (layout Can be used directly with time zone Parse)
time.ParseInLocation("2006-01-02 15:04:05", "2017-05-11 14:06:06", time.Local)
// func Unix(sec int64, nsec int64) Time
time.Unix(1e9, 0)
// func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
time.Date(2018, 1, 2, 15, 30, 10, 0, time.Local)
// func (t Time) In(loc *Location) Time The current time corresponds to the time in the specified time zone
loc, _ := time.LoadLocation("America/Los_Angeles")
fmt.Println(time.Now().In(loc))
// func (t Time) Local() Time
After getting to the point in time in order to meet the business and design, we need to convert to the format we need, which is called time formatting.
formatting
to string
To format a string, we need to use the time.Format method to convert it to the format we want
fmt.Println(time.Now().Format("2006-01-02 15:04:05")) // 2018-04-24 10:11:20
fmt.Println(time.Now().Format(time.UnixDate)) // Tue Apr 24 09:59:02 CST 2018
The Format function allows you to specify the format you want to use, and the time package also gives you some common 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"
)
注意: galang ZhongZhiDingDeTeDingShiJianGeShiWei "2006-01-02 15:04:05 -0700 MST", 为了记忆方便,按照美式时间格式 YueRiShiFenMiaoNian WaiJiaShi District 排列起来依次是 01/02 03:04:05PM ‘06 -0700,刚开始使用时需要注意。
to time stamp
func (t Time) Unix() int64
func (t Time) UnixNano() int64
fmt.Println(time.Now().Unix())
// Gets a timestamp for the specified date
dt, _ := time.Parse("2016-01-02 15:04:05", "2018-04-23 12:24:51")
fmt.Println(dt.Unix())
fmt.Println(time.Date(2018, 1,2,15,30,10,0, time.Local).Unix())
other
The time package also provides 1 common methods that cover most businesses, not least the method name that tells you what a representative means.
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
Time period (Duartion)
After introducing the time point, let's introduce the time period, the Duartion type, which is also very common in our business.
// func ParseDuration(s string) (Duration, error)
tp, _ := time.ParseDuration("1.5s")
fmt.Println(tp.Truncate(1000), tp.Seconds(), tp.Nanoseconds())
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 // 4 Give up 5 Into the
func (d Duration) Truncate(m Duration) Duration // Take down the whole
Time zone (Location)
We are going to introduce the function related to time zone 1
// The default UTC
loc, err := time.LoadLocation("")
// Time zone set by the server, 1 As for the CST
loc, err := time.LoadLocation("Local")
// Los Angeles, USA PDT
loc, err := time.LoadLocation("America/Los_Angeles")
// Gets the point in time for the specified time zone
local, _ := time.LoadLocation("America/Los_Angeles")
fmt.Println(time.Date(2018,1,1,12,0,0,0, local))
Can be in the $GOROOT lib/time/zoneinfo zip file under see all time zones.
Time operation
Ok, so we're done with the basic types, and now we're going to start with the time-related functions that we use a lot in our day-to-day business.
// func Sleep(d Duration) Sleep how long, sleep in a blocked state, subsequent programs cannot execute
time.Sleep(time.Duration(10) * time.Second)
// func After(d Duration) <-chan Time non-blocking , Can be used to delay
time.After(time.Duration(10) * time.Second)
// func Since(t Time) Duration The interval between two points in time
start := time.Now()
fmt.Println(time.Since(start)) // Is equivalent to Now().Sub(t) . Can be computed 1 The elapsed time of a segment of business
func Until(t Time) Duration // Is equivalent to t.Sub(Now()) . t The interval from the current time
// func (t Time) Add(d Duration) Time
fmt.Println(dt.Add(time.Duration(10) * time.Second)) // add
func (t Time) Sub(u Time) Duration // Reduction of
// func (t Time) AddDate(years int, months int, days int) Time
fmt.Println(dt.AddDate(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 compare points in time Equal function
We've roughly covered most of the functions that involve time points and time periods, and then we'll do some demos with some usage scenarios.
Usage scenarios
Date time difference
dt1 := time.Date(2018, 1, 10, 0, 0, 1, 100, time.Local)
dt2 := time.Date(2018, 1, 9, 23, 59, 22, 100, time.Local)
// Don't worry about time zones, go It will be converted to a timestamp for calculation
fmt.Println(dt1.Sub(dt2))
Before and after operations based on the current time
now := time.Now()
// 1 Years and 1 months 1 Days after the
fmt.Println(now.Date(1,1,1))
// 1 After a while
fmt.Println(now.Add(time.Duration(10)*time.Minute))
// Calculate the number of days between the two time points
dt1 = time.Date(dt1.Year(), dt1.Month(), dt1.Day(), 0, 0, 0, 0, time.Local)
dt2 = time.Date(dt2.Year(), dt2.Month(), dt2.Day(), 0, 0, 0, 0, time.Local)
fmt.Println(int(math.Ceil(dt1.Sub(dt2).Hours() / 24)))
Time zone conversion
fmt.Println(time.Now().Format("2006-01-02 15:04:05")) // 2018-04-24 10:11:20
fmt.Println(time.Now().Format(time.UnixDate)) // Tue Apr 24 09:59:02 CST 2018
0
Compare two points in time
fmt.Println(time.Now().Format("2006-01-02 15:04:05")) // 2018-04-24 10:11:20
fmt.Println(time.Now().Format(time.UnixDate)) // Tue Apr 24 09:59:02 CST 2018
1
Set the execution time
Used in combination with the select function, time.After can be used to handle program timeout Settings
fmt.Println(time.Now().Format("2006-01-02 15:04:05")) // 2018-04-24 10:11:20
fmt.Println(time.Now().Format(time.UnixDate)) // Tue Apr 24 09:59:02 CST 2018
2
Ticker type
The Ticker type contains 1 channel, and sometimes we run into a business that is executed every 1 period of time (such as setting the heartbeat time, etc.) and we can use it, which is a repetitive process
// Can't cancel
tick := time.Tick(1 * time.Minute)
for _ = range tick {
// do something
}
// By calling ticker.Stop cancel
ticker := time.NewTicker(1 * time.Minute)
for _ = range tick {
// do something
}
Timer type
The Timer type is used to represent a single event. When the set time expires, send the current time to channel
fmt.Println(time.Now().Format("2006-01-02 15:04:05")) // 2018-04-24 10:11:20
fmt.Println(time.Now().Format(time.UnixDate)) // Tue Apr 24 09:59:02 CST 2018
4
Both of the above functions can use Reset. The one important thing to note with Reset is that when using Reset, you need to ensure that the ES153en.C channel is not called until it is released to prevent resource contention. This can be done in the following ways
fmt.Println(time.Now().Format("2006-01-02 15:04:05")) // 2018-04-24 10:11:20
fmt.Println(time.Now().Format(time.UnixDate)) // Tue Apr 24 09:59:02 CST 2018
5
reference
package time
golang accumulation - use of time, time zone, format