time
Il pacchetto time fornisce funzioni e metodi relativi a tempo e calendario.
La funzione time.Now() può ottenere l'ora corrente
func Now() Timenow := time.Now()
fmt.Println(now)
//2022-11-17 10:00:18.6983438 +0800 CST m=+0.007095001Il tipo di dato restituito è la struct Time, che contiene moltissimi metodi per operazioni temporali.
func (t *Time) nsec() int32 // Nanosecondi
func (t *Time) sec() int64 // Secondi
func (t *Time) unixSec() // Restituisce i secondi nel formato tempo Unix
func (t *Time) addSec(d int64) // Aggiunge secondi
func (t *Time) setLoc(loc *Location) // Imposta la regione
func (t *Time) stripMono() // Rimuove la lettura dell'orologio monotono del tempo
func (t Time) After(u Time) // Verifica se un tempo è dopo un altro
func (t Time) Before(u Time) bool // Verifica se un tempo è prima di un altro
func (t Time) Equal(u Time) bool // Verifica se due tempi rappresentano lo stesso istante
func (t Time) Sub(u Time) Duration // Calcola la differenza tra due tempi
func (t Time) Add(d Duration) Time // Aggiunge un intervallo di tempoUnità di Tempo
Il pacchetto time contiene costanti di unità di tempo di base
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
)Il loro tipo è time.Duration, l'unità minima è il nanosecondo, la massima è l'ora.
Formattazione
Il tipo tempo può essere formattato in output, ma va notato che in Go il modello di formattazione non è il comune yyyy-mm-dd, ma si basa sul tempo di nascita di Go. Il tempo di nascita di Go è il 2 gennaio 2006 alle 15:04.
Esempio
now := time.Now()Output formattato 24 ore
fmt.Println(now.Format("2006-01-02 15:04:05 Monday Jan"))
//2022-11-17 10:44:48 Thursday NovOutput solo data
fmt.Println(now.Format("2006-01-02"))
//2022-11-17Output solo ora formato 12 ore
fmt.Println(now.Format("15:04:05 PM"))
//10:48:47 AMAnalisi del Tempo
Spesso abbiamo la necessità di convertire una stringa temporale in un formato specifico nella struct temporale di Go. Ecco cosa faremo.
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())
}Output finale
2012-10-12 00:00:00 +0800 CSTTimer
Timer è un cronometro che espone un channel. Quando il tempo specificato scade, il channel riceverà un messaggio e si chiuderà.
func NewTimer(d Duration) *TimerÈ possibile creare un nuovo cronometro tramite 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.007908001Dopo aver utilizzato il timer, è necessario chiuderlo tempestivamente.
Ticker
Ticker è un timer, la differenza con timer è che timer è una tantum, mentre Ticker si attiva periodicamente.
func NewTicker(d Duration) *TickerÈ possibile creare un nuovo timer tramite 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.016742001Allo stesso modo, dopo aver utilizzato il ticker, è necessario chiuderlo tempestivamente.
Sleep
time.Sleep() può mettere la goroutine corrente in stato di sospensione per un certo periodo di tempo. Durante questo periodo, la goroutine verrà bloccata fino al ripristino dello stato di esecuzione.
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.013496401Questo programma si bloccherà per due secondi dopo l'output di start, quindi outputterà end.
