time
El paquete time proporciona funciones y métodos relacionados con el tiempo y el calendario.
La función time.Now() puede obtener la hora actual
func Now() Timenow := time.Now()
fmt.Println(now)
//2022-11-17 10:00:18.6983438 +0800 CST m=+0.007095001Su tipo de dato devuelto es la estructura Time, que contiene muchos métodos de operación de tiempo.
func (t *Time) nsec() int32 //Nanosegundos
func (t *Time) sec() int64 //Segundos
func (t *Time) unixSec() //Devuelve los segundos en formato de tiempo Unix
func (t *Time) addSec(d int64) //Agregar segundos
func (t *Time) setLoc(loc *Location) //Establecer región
func (t *Time) stripMono() //Eliminar la lectura del reloj monótono del tiempo
func (t Time) After(u Time) //Determinar si un tiempo está después de otro
func (t Time) Before(u Time) bool //Determinar si un tiempo está antes de otro
func (t Time) Equal(u Time) bool //Determinar si dos tiempos representan el mismo instante
func (t Time) Sub(u Time) Duration //Obtener la diferencia entre dos tiempos
func (t Time) Add(d Duration) Time //Agregar un intervalo de tiempoUnidades de tiempo
El paquete time contiene constantes de unidades de tiempo básicas
const (
minDuration Duration = -1 << 63
maxDuration Duration = 1<<63 - 1
)
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)Su tipo es time.Duration, la unidad mínima es nanosegundo y la máxima es hora.
Formateo
El tipo de tiempo se puede formatear, pero debe tenerse en cuenta que la plantilla de formateo en Go no es el común yyyy-mm-dd, sino que usa el tiempo de nacimiento de Go como plantilla. El tiempo de nacimiento de Go es el 2 de enero de 2006 a las 15:04.
Ejemplo
now := time.Now()Formateo de 24 horas
fmt.Println(now.Format("2006-01-02 15:04:05 Monday Jan"))
//2022-11-17 10:44:48 Thursday NovSolo salida de fecha
fmt.Println(now.Format("2006-01-02"))
//2022-11-17Solo salida de hora en formato de 12 horas
fmt.Println(now.Format("15:04:05 PM"))
//10:48:47 AMAnálisis de tiempo
A menudo tenemos la necesidad de convertir una cadena de tiempo en una estructura de tiempo de Go según un formato determinado. Esto es lo que haremos a continuación.
func main() {
location, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
fmt.Println(err)
return
}
inLocation, err := time.ParseInLocation("2006/01/02", "2012/10/12", location)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(inLocation.String())
}Salida final
2012-10-12 00:00:00 +0800 CSTTimer
Timer es un temporizador que expone un canal. Cuando se alcanza el tiempo especificado, el canal recibirá un mensaje y se cerrará.
func NewTimer(d Duration) *TimerSe puede crear un nuevo temporizador a través de time.NewTimer()
func main() {
timer := time.NewTimer(time.Second)
defer timer.Stop()
select {
case t := <-timer.C:
fmt.Println(t)
}
}2023-09-25 21:25:03.5696803 +0800 CST m=+1.007908001Después de usar el timer, debe cerrarse a tiempo.
Ticker
Ticker es un temporizador periódico. La diferencia con timer es que timer es de una sola vez, mientras que Ticker se activa periódicamente.
func NewTicker(d Duration) *TickerSe puede crear un nuevo temporizador a través de time.NewTicker()
func main() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for i := 0; i < 3; i++ {
select {
case t := <-ticker.C:
fmt.Println(t)
}
}
}2023-09-25 21:29:20.4429256 +0800 CST m=+1.009508401
2023-09-25 21:29:21.4512075 +0800 CST m=+2.017790301
2023-09-25 21:29:22.4501592 +0800 CST m=+3.016742001De la misma manera, después de usar el ticker, también debe cerrarse a tiempo.
sleep
time.Sleep() puede hacer que la goroutine actual esté en estado suspendido durante un período de tiempo. Durante este período, la goroutine se bloqueará hasta que se restablezca el estado de ejecución.
func Sleep(d Duration)func main() {
start := time.Now()
fmt.Println(start)
time.Sleep(time.Second * 2)
end := time.Now()
fmt.Println(end)
}2023-09-25 21:36:35.7229057 +0800 CST m=+0.001627901
2023-09-25 21:36:37.7347742 +0800 CST m=+2.013496401Este programa se bloqueará durante dos segundos después de imprimir start, y luego imprimirá end.
