This is the 10th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Here are some basic uses of time in Golang, starting with several types of time.

Time can be divided into points in time and periods, and Golang provides the following two basic types:

  • Point in Time (Time)
  • Time (Duration)

In addition Golang also offers the following types to do some specific business:

  • Time zone (Location)
  • Ticker
  • Timer(Timer)

Point in Time (Time)

All the time-related businesses we use are based on the point and extend, two points constitute a time period, and most applications do logic processing around these points and surfaces.

Initialize the

Golang provides the following initialization methods for different parameter types:

// func Now() Time
fmt.Println(time.Now())

// func Parse(layout, value string) (Time, error)
time.Parse("The 2016-01-02 15:04:05"."The 2018-04-23 12:24:51")

// func ParseInLocation(layout, value string, loc *Location) (Time, error)
time.ParseInLocation("The 2006-01-02 15:04:05"."The 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 Indicates the Time In the specified Time zone
loc, _ := time.LoadLocation("America/Los_Angeles")
fmt.Println(time.Now().In(loc))

// func (t Time) Local() Time
Copy the code

formatting

After obtaining the point in time, we need to convert it to the format we need for business and design purposes, which is called time formatting.

to string

Format to string We need to use the time.format method to convert to the Format we want

fmt.Println(time.Now().Format("The 2006-01-02 15:04:05"))  / / the 2018-04-24 10:11:20
fmt.Println(time.Now().Format(time.UnixDate))         // Tue Apr 24 09:59:02 CST 2018
Copy the code

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 = "The 2006-01-02 T15:04:05. 999999999 z07: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." "
)
Copy the code

Note: The specific time format specified in Golang is 2006-01-02 15:04:05-0700 MST

to timestamp

func (t Time) Unix(a) int64
func (t Time) UnixNano(a) int64

fmt.Println(time.Now().Unix())

// Get a timestamp for the specified date
dt, _ := time.Parse("The 2016-01-02 15:04:05"."The 2018-04-23 12:24:51")
fmt.Println(dt.Unix())

fmt.Println(time.Date(2018.1.2.15.30.10.0, time.Local).Unix())
Copy the code

other

The Time package also provides some common methods:

func (t Time) Date(a) (year int, month Month, day int)
func (t Time) Clock(a) (hour, min, sec int)
func (t Time) Year(a) int
func (t Time) Month(a) Month
func (t Time) Day(a) int
func (t Time) Hour(a) int
func (t Time) Minute(a) int
func (t Time) Second(a) int
func (t Time) Nanosecond(a) int
func (t Time) YearDay(a) int
func (t Time) Weekday(a) Weekday
func (t Time) ISOWeek(a) (year, week int)
func (t Time) IsZero(a) bool
func (t Time) Local(a) Time
func (t Time) Location(a) *Location
func (t Time) Zone(a) (name string, offset int)
func (t Time) Unix(a) int64
Copy the code

Time period (Duartion)

After introducing the time point, we will introduce the Duartion type, which is also a common type in services.

// func ParseDuration(s string) (Duration, error)
tp, _ := time.ParseDuration("1.5 s")
fmt.Println(tp.Truncate(1000), tp.Seconds(), tp.Nanoseconds())

func (d Duration) Hours(a) float64
func (d Duration) Minutes(a) float64
func (d Duration) Seconds(a) float64
func (d Duration) Nanoseconds(a) int64
func (d Duration) Round(m Duration) Duration// Round off
func (d Duration) Truncate(m Duration) Duration// Round down
Copy the code

Time zone (Location)

Let’s introduce some functions related to time zones:

/ / the default UTC
loc, err := time.LoadLocation("") 
// The time zone set by the server, usually CST
loc, err := time.LoadLocation("Local")
// PDT, Los Angeles, USA
loc, err := time.LoadLocation("America/Los_Angeles")

// Get the point in time in the specified time zone
local, _ := time.LoadLocation("America/Los_Angeles")
fmt.Println(time.Date(2018.1.1.12.0.0.0, local))
Copy the code

Time operation

// func Sleep(d Duration) How long to Sleep. When Sleep is blocked, subsequent programs cannot be executed
time.Sleep(time.Duration(10) * time.Second)

// func After(d Duration) <-chan Time Non-blocking, can be used for delay
time.After(time.Duration(10) * time.Second)

// func Since(t Time) Duration Interval between two Time points
start := time.Now()
fmt.Println(time.Since(start))   // Equivalent to Now().sub (t), can be used to calculate the elapsed time of a segment of business

func Until(t Time) Duration/ / equivalent to thet.Sub(Now()),tThe 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/ /

// 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 Equal

Copy the code

Common usage scenarios of the Golang Time package

Compare date time differences

dt1 := time.Date(2018.1.10.0.0.1.100, time.Local)
dt2 := time.Date(2018.1.9.23.59.22.100, time.Local)

// Do not care about the time zone, Go will be converted into a timestamp for calculation
fmt.Println(dt1.Sub(dt2))
Copy the code

Before and after operations based on the current time

now := time.Now()

// One year, one month and one day later
fmt.Println(now.Date(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)))
Copy the code

Time zone conversion

// Time. Local indicates the time zone of the current server
// Customize the local time
secondsEastOfUTC := int((8 * time.Hour).Seconds())
beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
fmt.Println(time.Date(2018.1.2.0.0.0.0, beijing))  // 2018-01-02 00:00:00 +0800 Beijing Time  

// Convert the current time to the specified time zone
fmt.Println(time.Now().In(beijing))

// The specified time is converted to the specified time zone
dt, err := time.ParseInLocation("The 2006-01-02 15:04:05"."The 2017-05-11 14:06:06", time.Local)

// The current time is in the zero hour zone
year, mon, day := time.Now().UTC().Date()     // 2018 April 24
hour, min, sec := time.Now().UTC().Clock()    47 15 / / 3
zone, _ := time.Now().UTC().Zone()            // UTC
Copy the code

Compare two points in time

dt := time.Date(2018.1.10.0.0.1.100, time.Local)
fmt.Println(time.Now().After(dt))     // true
fmt.Println(time.Now().Before(dt))    // false

The Equal function is recommended to determine whether two points in time are Equal
fmt.Println(dt.Equal(time.Now()))
Copy the code

Setting the execution time

Use the time.After function in combination with select to handle program timeouts:

select {
    case m := <- c:
    // do something
    case <- time.After(time.Duration(1)*time.Second):
    fmt.Println("time out")}Copy the code

Ticker type

The Ticker type contains a channel that a scheduled task can use to process.

// Cannot cancel
tick := time.Tick(1 * time.Minute)
for _ = range tick {
    // do something
}

// Cancel by calling ticker.stop
ticker := time.NewTicker(1 * time.Minute)
for _ = range tick {
    // do something
}
Copy the code

The Timer type

The Timer type represents a single event that sends the current time to a channel when the set time expires. We can create this in either of the following ways:

func AfterFunc(d Duration, f func(a)) *Timer// Specify the function to be specified after a period of time
func NewTimer(d Duration) *Timer
Copy the code

The Reset function can be used for both functions. The Reset function can be used only when the t.C channel is released. To prevent resource contention, you can use the following methods:

if! t.Stop() { <-t.C } t.Reset(d)Copy the code