Go language pack time

Go time basis of the language pack

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.Time type represents time. We can function to get the current time object via time.Now (), then the object of acquisition time information such as the date when the minutes and seconds. 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.Duration is a packet type defined time, which represents the elapsed time between two points of time in nanoseconds. time.Duration 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.Duration represents 1 nanosecond, time.Second represents 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

Two time-off are the same, the impact would consider time 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

It is a channel (channel) using essentially time.Tick (time interval) setting a timer, the timer.

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

Time Format

There comes a time type method Format format, to note that Go language is not a common template formatting time Ymd H: M: S Go instead to use the birth time January 2, 2006 15:04 (memory of formulas 20061234). 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))
Published 60 original articles · won praise 168 · views 60000 +

Guess you like

Origin blog.csdn.net/qq_43518645/article/details/104268827