time Go language of the standard library

The time and date are often used in our programming, this paper introduces the basic use of the built-in time Go language package.

time package

package provides a time display function of time and measurement. The calculation uses the Gregorian calendar.

Time Type

time.TimeType represents time. We can time.Now()every minute and other information to get the current time function of the object, then the object of acquisition time date. Sample code is as follows:

func timeDemo() {
    now := time.Now() //获取当前时间
    fmt.Printf("current time:%v\n", now)

    year := now.Year()     //年
    month := now.Month()   //月
    day := now.Day()       //日
    hour := now.Hour()     //小时
    minute := now.Minute() //分钟
    second := now.Second() //秒
    fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}

Timestamp

Timestamp is from January 1, 1970 (08: 00: 00GMT) the total number of milliseconds to the current time. It is also called Unix time (UnixTimestamp).

Sample Code acquires a time stamp based on the time the object is as follows:

func timestampDemo() {
    now := time.Now()            //获取当前时间
    timestamp1 := now.Unix()     //时间戳
    timestamp2 := now.UnixNano() //纳秒时间戳
    fmt.Printf("current timestamp1:%v\n", timestamp1)
    fmt.Printf("current timestamp2:%v\n", timestamp2)
}

Use time.Unix()function can be converted to time stamp the time format.

func timestampDemo2(timestamp int64) {
    timeObj := time.Unix(timestamp, 0) //将时间戳转为时间格式
    fmt.Println(timeObj)
    year := timeObj.Year()     //年
    month := timeObj.Month()   //月
    day := timeObj.Day()       //日
    hour := timeObj.Hour()     //小时
    minute := timeObj.Minute() //分钟
    second := timeObj.Second() //秒
    fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}

time interval

time.DurationA timepackage of a defined type, which represents the elapsed time between two points of time in nanoseconds. time.DurationIt represents a time interval, the longest time period that can be represented approximately 290 years.

Constant time interval of the packet type defined as follows:

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

For example: time.Durationit represents 1 nanosecond, time.Secondrepresents one second.

Time operation

Add

We may encounter requires time + time intervals in the daily needs of the encoding process, the time has provided language objects Go Add method is as follows:

func (t Time) Add(d Duration) Time

For example, seek time after one hour:

func main() {
    now := time.Now()
    later := now.Add(time.Hour) // 当前时间加1小时后的时间
    fmt.Println(later)
}

Sub

Seeking the difference between the two times:

func (t Time) Sub(u Time) Duration

Return to a time period tu. If the result exceeds the maximum value / minimum Duration may represent will return the maximum / minimum. To obtain the time point td (d of Duration), may be used t.Add (-d).

Equal

func (t Time) Equal(u Time) bool

Determine whether the same two time, time will take into account the impact zone, and therefore different time zones standard time can be more accurate. The present method and with t == u, this approach will compare the location and time zone information.

Before

func (t Time) Before(u Time) bool

If t represents the time point before u, returns true; otherwise it returns false.

After

func (t Time) After(u Time) bool

If t represents the time point after u, returns true; otherwise it returns false.

Timer

Used time.Tick(时间间隔)to set the timer, the timer is essentially a channel (channel).

func tickDemo() {
    ticker := time.Tick(time.Second) //定义一个1秒间隔的定时器
    for i := range ticker {
        fmt.Println(i)//每秒都会执行的任务
    }
}

Time Format

Time type has a built-in method Formatto format Go to note that the language is not a common template formatting time Y-m-d H:M:Sbut the use Go's Birth Date January 2, 2006 15:04 (remember formulas for the 200 612 34). Perhaps this is romantic technician bar.

NOTE: If you want to format is 12-hour mode, specify PM.

func formatDemo() {
    now := time.Now()
    // 格式化的模板为Go的出生时间2006年1月2号15点04分 Mon Jan
    // 24小时制
    fmt.Println(now.Format("2006-01-02 15:04:05.000 Mon Jan"))
    // 12小时制
    fmt.Println(now.Format("2006-01-02 03:04:05.000 PM Mon Jan"))
    fmt.Println(now.Format("2006/01/02 15:04"))
    fmt.Println(now.Format("15:04 2006/01/02"))
    fmt.Println(now.Format("2006/01/02"))
}

Analytical time string format

now := time.Now()
fmt.Println(now)
// 加载时区
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
    fmt.Println(err)
    return
}
// 按照指定时区和指定格式解析字符串时间
timeObj, err := time.ParseInLocation("2006/01/02 15:04:05", "2019/08/04 14:15:20", loc)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println(timeObj)
fmt.Println(timeObj.Sub(now))

Exercises:

  1. Obtain the current time, the output is formatted 2017/06/19 20:30: 05` format.
  2. Perform statistical programming piece of code takes time, accurate to the microsecond units.

Guess you like

Origin www.cnblogs.com/nickchen121/p/11517467.html