Operación y procesamiento del tiempo de Golang





Las operaciones relacionadas con el tiempo involucran principalmente el paquete de tiempo. La estructura de datos principal es el tiempo. El tiempo, como sigue:

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

! [Inserte aquí la descripción de la imagen] (https://img-blog.csdnimg.cn/20210115092428347.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibizeG9n=




1 Obtener funciones relacionadas con el tiempo


1.1 Obtener la hora actual

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

Resultado de salida:

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

1.2 Obtenga el año actual, mes, día, hora, minuto, segundo, día de la semana, día del año, 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())

Resultado de salida:

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

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

Friday
15
Local

1.3 Formato de tiempo

El idioma Go proporciona la función de formato de hora Format (). Cabe señalar que la plantilla de tiempo de formato de idioma Go no es el Ymd H: i: s común, sino 2006-01-02 15:04:05, que también es fácil para recordar (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"))

Resultado de salida:

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




2 Conversión entre marca de tiempo y cadena de fecha

¿Cómo convertir la marca de tiempo al formato de fecha? Debe convertir la marca de tiempo a la hora. Primero escriba la hora y luego formatee en un formato de fecha.


2,1 segundos, marca de tiempo en nanosegundos ==> tiempo. Tipo de tiempo

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

Resultado de salida:

2021-01-15 09:10:16

2.2 Especificar tiempo ==> tiempo.Tipo de tiempo

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))

Resultado de salida:

2011-03-12 15:30:20

2.3 Cadena de fecha ==> hora.Tipo de hora

	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)

Resultado de salida:

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

Como puede ver, time.Now () usa CST (hora estándar de China), mientras que time.Parse () tiene como valor predeterminado UTC (zona horaria cero), que tiene una diferencia de 8 horas. y entoncesTime.ParseInLocation () se usa comúnmente al analizar, y se puede especificar la zona horaria




3 Cálculo y comparación de fechas

En lo que respecta al cálculo de la fecha, debemos mencionar un nuevo tipo de Duración proporcionada por el paquete de tiempo. El código fuente se define de la siguiente manera:

tipo Duración int64

El tipo subyacente es int64, que representa un período de tiempo, y la unidad es nanosegundos.

3.1 Cálculo de tiempo en 24 horas

	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

Resultado de salida:

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

Se introducen dos funciones adicionales time.Since () y time.Until ():

// Devuelve la diferencia de tiempo entre la hora actual yt, el valor devuelto es Duración tiempo.
Desde (t Tiempo) Duración

// Devuelve la diferencia de tiempo entre t y la hora actual, el valor devuelto es
Tiempo de duración. Hasta (t Tiempo) Duración

Ejemplo:

	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))

Resultado de salida:

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 Cálculo de tiempo después de 24 horas

Cuando se trata de cálculos que no sean de un día, necesita usar time.AddDate (), el prototipo de función:

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

Por ejemplo, después de un año y un día al mes , puede hacer:

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

Obtenga 2 días antes de la hora:

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 Comparación de fechas

Hay tres tipos de comparaciones de fechas: antes, después e iguales.

// Si el punto de tiempo representado por t está antes de u, devuelve verdadero; de lo contrario, devuelve falso.
func (t Time) Before (u Time) bool

// Si el punto de tiempo representado por t es posterior a u, devuelve verdadero; de lo contrario, devuelve falso.
func (t Time) After (u Time) bool

// Compara si el tiempo es igual, devuelve verdadero si es igual; de lo contrario, devuelve falso.
func (t Tiempo) Igual (u Tiempo) 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))

Resultado de salida:

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 paquetes comunes.

4.1 Formato de fecha ==> marca de tiempo

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 Obtener el formato de fecha y hora actual

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

4.3 Marca de tiempo ==> Formato de fecha

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

Supongo que te gusta

Origin blog.csdn.net/QiuHaoqian/article/details/112646901
Recomendado
Clasificación