Golang time operation and processing





Time-related operations mainly involve the time package. The core data structure is time.Time, as follows:

type Time struct {
    
    
    wall uint64
    ext  int64
    loc *Location
}

![Insert the picture description here](https://img-blog.csdnimg.cn/20210115092428347.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4FubdV0L=FF_size




1 Get time related functions


1.1 Get the current time

// 返回当前时间,注意此时返回的是 time.Time 类型
now := time.Now()
fmt.Println(now)
// 当前时间戳
fmt.Println(now.Unix())
// 纳秒级时间戳
fmt.Println(now.UnixNano())
// 时间戳小数部分 单位:纳秒
fmt.Println(now.Nanosecond())

Output result:

2021-01-10 14:56:15.930562 +0800 CST m=+0.000124449
1610261775
1610261775930562000
930562000

1.2 Get the current year, month, day, hour, minute, second, day of the week, day of the year, etc.

now := time.Now()

// 返回日期
year, month, day := now.Date()

fmt.Printf("year:%d, month:%d, day:%d\n", year, month, day)
// 年
fmt.Println(now.Year())
// 月
fmt.Println(now.Month())
// 日
fmt.Println(now.Day())

// 时分秒
hour, minute, second := now.Clock()
fmt.Printf("hour:%d, minute:%d, second:%d\n", hour, minute, second)

// 时
fmt.Println(now.Hour())
// 分
fmt.Println(now.Minute())
// 秒
fmt.Println(now.Second())

// 返回星期
fmt.Println(now.Weekday())
// 返回一年中对应的第几天
fmt.Println(now.YearDay())
// 返回时区
fmt.Println(now.Location())

Output result:

year:2021, month:1, day:15
2021
January
15

hour:9, minute:5, second:3
9
5
3

Friday
15
Local

1.3 Format time

The Go language provides the time formatting function Format(). It should be noted that the Go language formatting time template is not the common Ymd H:i:s, but 2006-01-02 15:04:05, which is also easy to remember (2006 1 2 3 4 5).

now := time.Now()

fmt.Println(now.Format("2006-01-02 15:03:04"))
fmt.Println(now.Format("2006-01-02"))
fmt.Println(now.Format("15:03:04"))
fmt.Println(now.Format("2006/01/02 15:04"))
fmt.Println(now.Format("15:04 2006/01/02"))

Output result:

2021-01-15 09:09:07
2021-01-15
09:09:07
2021/01/15 09:07
09:07 2021/01/15




2 Conversion between timestamp and date string

How to convert the timestamp to date format? You need to convert the timestamp to the time.Time type first, and then format it into a date format.


2.1 Seconds, nanosecond timestamp ==> time.Time type

now := time.Now()
layout := "2006-01-02 15:04:05"
t := time.Unix(now.Unix(),0)    // 参数分别是:秒数,纳秒数, 返回time.Time类型
fmt.Println(t.Format(layout))

Output result:

2021-01-15 09:10:16

2.2 Specify time ==> time.Time type

now := time.Now()
layout := "2006-01-02 15:04:05"

// 根据指定时间返回 time.Time 类型
// 分别指定年,月,日,时,分,秒,纳秒,时区
t := time.Date(2011, time.Month(3), 12, 15, 30, 20, 0, now.Location())
fmt.Println(t.Format(layout))

Output result:

2011-03-12 15:30:20

2.3 Date string ==> time.Time type

	t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2021-01-10 15:01:02", time.Local)
	fmt.Println(t)
	
	// time.Local 指定本地时间, 解析的时候需要特别注意时区的问题
	fmt.Println(time.Now())
	fmt.Println(time.Now().Location())
	t, _ = time.Parse("2006-01-02 15:04:05", "2021-01-10 15:01:02")
	fmt.Println(t)

Output result:

2021-01-15 15:01:02 +0800 CST
2021-01-15 09:20:58.604154 +0800 CST m=+0.025924201
Local
2021-01-15 15:01:02 +0000 UTC

As you can see, time.Now() uses CST (China Standard Time), while time.Parse() defaults to UTC (zero time zone), which is 8 hours apart. and soTime.ParseInLocation() is commonly used when parsing, and the time zone can be specified




3 Date calculation and comparison

When it comes to date calculation, we have to mention a new type of Duration provided by the time package. The source code is defined as follows:

type Duration int64

The underlying type is int64, which represents a period of time, and the unit is nanoseconds.

3.1 Time calculation within 24 hours

	now := time.Now()
	fmt.Println(now) // 2021-01-15 09:29:24.3377864 +0800 CST m=+0.003989801

	// 1小时1分1s之后
	t1, _ := time.ParseDuration("1h1m1s")
	fmt.Println(t1) // 1h1m1s
	m1 := now.Add(t1)
	fmt.Println(m1) // 2021-01-15 10:30:25.3377864 +0800 CST m=+3661.003989801

	// 1小时1分1s之前
	t2, _ := time.ParseDuration("-1h1m1s")
	m2 := now.Add(t2) 
	fmt.Println(m2) // 2021-01-15 08:28:23.3377864 +0800 CST m=-3660.996010199

	// 3小时之前
	t3, _ := time.ParseDuration("-1h")
	m3 := now.Add(t3 * 3)
	fmt.Println(m3) // 2021-01-15 06:29:24.3377864 +0800 CST m=-10799.996010199

	// 10 分钟之后
	t4, _ := time.ParseDuration("10m")
	m4 := now.Add(t4)
	fmt.Println(m4) // 2021-01-15 09:39:24.3377864 +0800 CST m=+600.003989801

	// Sub 计算两个时间差
	sub1 := now.Sub(m3)
	fmt.Println(sub1.Hours())   // 相差小时数 :3
	fmt.Println(sub1.Minutes()) // 相差分钟数 :180

Output result:

2021-01-15 09:29:24.3377864 +0800 CST m=+0.003989801
1h1m1s
2021-01-15 10:30:25.3377864 +0800 CST m=+3661.003989801
2021-01-15 08:28:23.3377864 +0800 CST m=-3660.996010199
2021-01-15 06:29:24.3377864 +0800 CST m=-10799.996010199
2021-01-15 09:39:24.3377864 +0800 CST m=+600.003989801
3
180

Two additional functions time.Since() and time.Until() are introduced:

// Return the time difference between the current time and t, the return value is Duration
time.Since(t Time) Duration

// Return the time difference between t and the current time, the return value is Duration
time.Until(t Time) Duration

Example:

	now := time.Now()
	fmt.Println(now)

	t1, _ := time.ParseDuration("-1h")
	m1 := now.Add(t1)
	fmt.Println(m1)
	
	fmt.Println(time.Since(m1))
	fmt.Println(time.Until(m1))

Output result:

2021-01-15 09:36:00.434253 +0800 CST m=+0.004987801
2021-01-15 08:36:00.434253 +0800 CST m=-3599.995012199
1h0m0.0309167s
-1h0m0.0309167s

3.2 Calculation of time beyond 24 hours

When it comes to calculations other than one day, you need to use time.AddDate(), the function prototype:

func (t Time) AddDate(years int, months int, days int) Time

For example, after a year and a day a month time, you can do:

now := time.Now()
fmt.Println(now) // 2021-01-15 09:39:23.8663871 +0800 CST m=+0.004987101

m1 := now.AddDate(1,1,1)
fmt.Println(m1) // 2022-02-16 09:39:23.8663871 +0800 CST

Get 2 days before time:

now := time.Now()
fmt.Println(now) // 2021-01-15 09:40:15.1981765 +0800 CST m=+0.005983001

m1 := now.AddDate(0,0,-2)
fmt.Println(m1) // 2021-01-13 09:40:15.1981765 +0800 CST

3.3 Date comparison

There are three types of date comparisons: before, after and equal.

// If the time point represented by t is before u, return true; otherwise, return false.
func (t Time) Before(u Time) bool

// If the time point represented by t is after u, return true; otherwise, return false.
func (t Time) After(u Time) bool

// Compare whether the time is equal, return true if equal; otherwise return false.
func (t Time) Equal(u Time) bool

now := time.Now()
fmt.Println(now)

// 1小时之后
t1, _ := time.ParseDuration("1h")
m1 := now.Add(t1)
fmt.Println(m1)

fmt.Println(m1.After(now))
fmt.Println(now.Before(m1))
fmt.Println(now.Equal(m1))

Output result:

2021-01-15 09:44:04.875319 +0800 CST m=+0.003984401
2021-01-15 10:44:04.875319 +0800 CST m=+3600.003984401

true
true
false




4 Common packages.

4.1 Date format ==> timestamp

func TimeStr2Time(fmtStr,valueStr, locStr string) int64 {
    
    
    loc := time.Local
    if locStr != "" {
    
    
        loc, _ = time.LoadLocation(locStr) // 设置时区
    }
    if fmtStr == "" {
    
    
        fmtStr = "2006-01-02 15:04:05"
    }
    t, _ := time.ParseInLocation(fmtStr, valueStr, loc)
    return t.Unix()
}

4.2 Get the current time and date format

func GetCurrentFormatStr(fmtStr string) string {
    
    
    if fmtStr == "" {
    
    
        fmtStr = "2006-01-02 15:04:05"
    }
    return time.Now().Format(fmtStr)
}

4.3 Timestamp ==> Date format

func Sec2TimeStr(sec int64, fmtStr string) string {
    
    
    if fmtStr == "" {
    
    
        fmtStr = "2006-01-02 15:04:05"
    }
    return time.Unix(sec, 0).Format(fmtStr)
}

Guess you like

Origin blog.csdn.net/QiuHaoqian/article/details/112646901