当前位置:网站首页>Time processing of basic library in go
Time processing of basic library in go
2022-07-24 11:51:00 【Ch3n】
time package
time The package provides functions for displaying and measuring time . The calendar is calculated in the Gregorian calendar .
Time type
time.Time Type represents time . We can go through time.Now() Function to get the current time object , Then obtain the date, month, hour, minute, second and other information of the time object . The sample code is as follows :
package main
import (
"fmt"
"time"
)
func main() {
// Get the current time 2022-07-19 10:03:42.70981 +0800 CST m=+0.000080935
now := time.Now()
fmt.Println(now)
fmt.Println(now.Year())
fmt.Println(now.Month())
fmt.Println(now.Day())
fmt.Println(now.Hour())
fmt.Println(now.Minute())
fmt.Println(now.Second())
}
Time stamp
The time stamp is from 1970 year 1 month 1 Japan (08:00:00GMT) The total number of milliseconds to the current time . It's also called Unix Time stamp (UnixTimestamp).
The sample code for obtaining time stamp based on time object is as follows :
package main
import (
"fmt"
"time"
)
func main() {
// Get the current time 2022-07-19 10:03:42.70981 +0800 CST m=+0.000080935
now := time.Now()
fmt.Println(now)
// Time stamp second
fmt.Println(now.Unix())
// Time stamp millisecond
fmt.Println(now.UnixMilli())
// Time stamp nanosecond
fmt.Println(now.UnixNano())
}
Use time.Unix() Function to convert a timestamp to a time format .
package main
import (
"fmt"
"time"
)
func main() {
// Get the current time 2022-07-19 10:03:42.70981 +0800 CST m=+0.000080935
now := time.Now()
fmt.Println(now)
// Timestamp to time type
unix := time.Unix(now.Unix(), 0)
fmt.Println(unix)
}
The time interval
time.Duration yes time A type of package definition , It represents the time between two time points , In nanoseconds .time.Duration A time interval , The longest period that can be expressed is about 290 year .
time The constants of the interval type defined in the package are as follows :
for example :time.Duration Express 1 nanosecond ,time.Second Express 1 second .
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
meanwhile ,time.Duration It provides a method to obtain the value of each time granularity
func (d Duration) Nanoseconds() int64 {
} // nanosecond
func (d Duration) Microseconds() int64 {
} // Microsecond
func (d Duration) Milliseconds() int64 {
} // millisecond
func (d Duration) Seconds() float64 {
} // second
func (d Duration) Minutes() float64 {
} // minute
func (d Duration) Hours() float64 {
} // Hours
Time operation
AddThe function is used to add / Reduce ( d A positive value of indicates an increase 、 Negative values indicate a decrease ) time.Time Duration of . For an instantaneous time , Increase or decrease the time above the specified nanosecond .func (t Time) Add(d Duration) Time {}SubFunction can get the duration between two time instants .func (t Time) Sub(u Time) Duration {}AddDateThe function is based on the year 、 The dimensions of month and day increase / Reduce time.Time Value .func (t Time) AddDate(years int, months int, days int) Time {}
Of course , Based on the current time instant time.Now() Computing is the most common requirement . therefore ,time The package also provides the following convenient time calculation functions .
SinceThe function istime.Now().Sub(t)A shortcut to .func Since(t Time) Duration {}UntilThe function ist.Sub(time.Now())A shortcut to .func Until(t Time) Duration {}
Examples of use
t := time.Now()
fmt.Println(t) // 2022-07-17 22:41:06.001567 +0800 CST m=+0.000057466
// Time increases 1 Hours
fmt.Println(t.Add(time.Hour * 1)) // 2022-07-17 23:41:06.001567 +0800 CST m=+3600.000057466
// Time increases 15 minute
fmt.Println(t.Add(time.Minute * 15))// 2022-07-17 22:56:06.001567 +0800 CST m=+900.000057466
// Time increases 10 Second
fmt.Println(t.Add(time.Second * 10))// 2022-07-17 22:41:16.001567 +0800 CST m=+10.000057466
// Time reduction 1 Hours
fmt.Println(t.Add(-time.Hour * 1)) // 2022-07-17 21:41:06.001567 +0800 CST m=-3599.999942534
// Time reduction 15 minute
fmt.Println(t.Add(-time.Minute * 15))// 2022-07-17 22:26:06.001567 +0800 CST m=-899.999942534
// Time reduction 10 Second
fmt.Println(t.Add(-time.Second * 10))// 2022-07-17 22:40:56.001567 +0800 CST m=-9.999942534
time.Sleep(time.Second * 5)
t2 := time.Now()
// Calculation t To t2 Duration of
fmt.Println(t2.Sub(t)) // 5.004318874s
// 1 Years later
t3 := t2.AddDate(1, 0, 0)
// Calculate from t To the current duration
fmt.Println(time.Since(t)) // 5.004442316s
// Calculate the duration from now to next year
fmt.Println(time.Until(t3)) // 8759h59m59.999864s
Time format
There's a way for time types Format format , In other languages , Generally, a general time template is used to format the time . for example Python, It USES %Y Represents the year 、%m Representative month 、%d Representative day, etc . It should be noted that Go Formatting time templates in languages is not common Y-m-d H:M:S But use Go The birth time of 2006 year 1 month 2 Number 15 spot 04 branch ( The formula of memory is 2006 1 2 3 4). Maybe this is the romance of technicians .
Add : If you want to format it as 12 Hour mode , Need to specify PM.
Formate The function is used to time.Time Object is converted into a time string according to the given layout .
now := time.Now()
// The formatted template is Go The birth time of 2006 year 1 month 2 Number 15 spot 04 branch Mon Jan
// 24 hourly
fmt.Println(now.Format("2006-01-02 15:04:05.000 Mon Jan"))
// 12 hourly
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"))
Parse The function is used to convert a time string into time.Time object .
now := time.Now()
fmt.Println(now)
// Load time zone
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
fmt.Println(err)
return
}
// Parse string time in the specified time zone and format
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))
边栏推荐
猜你喜欢

【C和指针第14章】预处理器

Record a garbage collection and analysis of gceasy

JVM visualvm: multi hop fault handling tool

Semaphore details
![[mathematical basis of Cyberspace Security Chapter 9] finite field](/img/2b/27ba1f3c6ec2ecff4538f9a63a79e8.jpg)
[mathematical basis of Cyberspace Security Chapter 9] finite field

JMeter if controller

动态内存管理

Linked list - Sword finger offer interview question 02.07. linked list intersection

Basic usage of GCC

Sorting out the ideas of data processing received by TCP server, and the note of select: invalid argument error
随机推荐
PDF处理还收费?不可能!
Semaphore详解
2 万字详解,吃透 ES!
Shell script
Agile? DevOps ?
Easy to understand ES6 (IV): template string
Recommended SSH cross platform terminal tool tabby
The difference between where and having
Hash - 349. Intersection of two arrays
An analysis of the CPU surge of an RFID tag management system in.Net
Chapter 1 Introduction
[markdown grammar advanced] make your blog more exciting (IV: set font style and color comparison table)
Microservice - eruka
makefile快速使用
Linked list - Sword finger offer interview question 02.07. linked list intersection
Common formulas and application scenarios of discrete distribution
DevOps及DevOps常用的工具介绍
Basic syntax of MySQL DDL and DML and DQL
L1-049 天梯赛座位分配
Best practice | using Tencent cloud AI character recognition to realize enterprise qualification certificate recognition