文章目录
- timeUnix:=time.Now().Unix() //已知的时间戳 formatTimeStr:=time.Unix(timeUnix,0).Format(“2006-01-02 15:04:05”) fmt.Println(formatTimeStr) //打印结果:2017-04-11 13:30:39
- formatTimeStr=”2017-04-11 13:33:37″ formatTime,err:=time.Parse(“2006-01-02 15:04:05”,formatTimeStr) if err==nil{ fmt.Println(formatTime) //打印结果:2017-04-11 13:33:37 +0000 UTC }
- formatTimeStr=”2017-04-11 13:33:37″ formatTime,err:=time.Parse(“2006-01-02 15:04:05”,formatTimeStr) utime := formatTime.Unix() if err == nil{ fmt.Println(utime) //打印结果:2017-04-11 13:33:37 +0000 UTC }
- currentTime := time.Now() startTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 0, 0, 0, 0, currentTime.Location()) fmt.Println(startTime) fmt.Println(startTime.Format(“2006/01/02 15:04:05”))
- currentTime := time.Now() endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location()) fmt.Println(endTime) fmt.Println(endTime.Format(“2006/01/02 15:04:05”))
- m, _ := time.ParseDuration(“-1m”) result := currentTime.Add(m) fmt.Println(result) fmt.Println(result.Format(“2006/01/02 15:04:05”))
- m, _ := time.ParseDuration(“-1h”) result := currentTime.Add(m) fmt.Println(result) fmt.Println(result.Format(“2006/01/02 15:04:05”))
- m, _ := time.ParseDuration(“1m”) result := currentTime.Add(m) fmt.Println(result) fmt.Println(result.Format(“2006/01/02 15:04:05”))
- m, _ := time.ParseDuration(“1h”) result := currentTime.Add(m) fmt.Println(result) fmt.Println(result.Format(“2006/01/02 15:04:05”))
- afterTime, _ := time.ParseDuration(“1h”) result := currentTime.Add(afterTime) beforeTime, _ := time.ParseDuration(“-1h”) result2 := currentTime.Add(beforeTime) m := result.Sub(result2) fmt.Printf(“%v 分钟 n”, m.Minutes()) h := result.Sub(result2) fmt.Printf(“%v小时 n”, h.Hours()) d := result.Sub(result2) fmt.Printf(“%v 天n”, d.Hours()/24)
- stringTime, _ := time.Parse(“2006-01-02 15:04:05”, “2019-12-12 12:00:00”) beforeOrAfter := stringTime.After(time.Now()) if true == beforeOrAfter { fmt.Println(“2019-12-12 12:00:00在当前时间之后!”) } else { fmt.Println(“2019-12-12 12:00:00在当前时间之前!”) }
- startTime := time.Now() time.Sleep(time.Second * 5) fmt.Println(“离现在过去了:”, time.Since(startTime))
- time.sleep单位为:1ns (纳秒)
- 1纳秒 =1000皮秒 1纳秒 =0.001 微秒 1纳秒 =0.000 001毫秒 1纳秒 =0.000 000 001秒 go用来指定睡眠时间的函数为time.Sleep,接口为: // Sleep pauses the current goroutine for at least the duration d. // A negative or zero duration causes Sleep to return immediately. func Sleep(d Duration) 传入的为一个Duration,所以如果想睡眠5s钟,不能直接写 time.Sleep(5) ,而应该写time.Sleep(5 * time.Second) 其中time.Second就是一个Duration类型,表示1s的时间间隔,乘系数5就得到5s的时间间隔。 除了time.Second外,go还提供了不同的时间单位: const ( Nanosecond Duration = 1 Microsecond = 1000 * Nanosecond Millisecond = 1000 * Microsecond Second = 1000 * Millisecond Minute = 60 * Second Hour = 60 * Minute ) 其中, Nanosecond表示1纳秒的时间间隔 Microsecond表示1微妙的时间间隔 Millisecond表示1毫秒的时间间隔 Second表示1秒的时间间隔 Minute表示1分钟的时间间隔 Hour表示1小时的时间间隔 想要睡眠的时间可以使用以上的常量自由组合,比如睡眠1小时10分5秒: time.Sleep(1*time.Hour + 10*time.Minute + 5*time.Second)
- package main import ( “fmt” “time” ) func main() { bT := time.Now() // 开始时间 time.Sleep(5*time.Second) eT := time.Since(bT) // 从开始到当前所消耗的时间 fmt.Println(“Run time: “, eT) } 运行结果: Run time: 5.001531s
- 在函数起始位置计算当前时间,在函数结束位置算出耗时。 package main import ( “fmt” “time” ) func sum(n int) int { var total int startT := time.Now()//计算当前时间 total := 0 for i:=1; i <= n; i++ { total += i } tc := time.Since(startT)//计算耗时 fmt.Printf(“time cost = %vn”, tc) return total } func main() { count := sum(100) fmt.Printf(“count = %vn”, count) } 运行结果: time cost = 250ns count = 5050
- 计算当前时间与计算耗时放在两处,难免显得丑陋,且不易阅读。如果有多个函数需要统计耗时,那么多处书写重复的两行代码会造成代码冗余。由于 Golang 提供了函数延时执行的功能,借助 defer ,可以通过函数封装的方式来避免代码冗余。 package main import ( “fmt” “time” ) //耗时统计函数 func timeCost(start time.Time){ tc:=time.Since(start) fmt.Printf(“time cost = %vn”, tc) } func sum(n int) int { defer timeCost(time.Now()) total := 0 for i:=1; i <= n; i++ { total += i } return total } func main() { count := sum(100) fmt.Printf(“count = %vn”, count) } 运行结果: time cost = 333ns count = 5050 通过输出可以看到sum()耗时增加了,因为增加了一次timeCost()函数调用。不过相比于函数封装带来的便利与代码美观,新增的耗时是微不足道可以接受的。
- 每次调用耗时统计函数timeCost()都需要传入time.Now(),重复书写time.Now()无疑造成了代码冗余。 在上面的基础上,进行进一步的封装,实现如下: package main import ( “fmt” “time” ) //耗时统计函数 func timeCost() func() { start := time.Now() return func() { tc:=time.Since(start) fmt.Printf(“time cost = %vn”, tc) } } func sum(n int) int { defer timeCost()()//注意,是对 timeCost()返回的函数进行调用,因此需要加两对小括号 total := 0 for i:=1; i <= n; i++ { total += i } return total } func main() { count := sum(100) fmt.Printf(“count = %vn”, count) } 运行结果: time cost = 1.204µs count = 5050
目录
- 1 获取当前时间
- 2 获取当前时间戳
- 3 获取当前时间的字符串格式
- 4 相互转化
- 4.1 时间戳转时间字符串 (int64 > string)
- 4.2 时间字符串转时间(string > Time)
- 4.3 时间字符串转时间戳 (string > int64)
- 5 时间计算
- 5.1 获取今天0点0时0分的时间戳
- 5.2 获取今天23:59:59秒的时间戳
- 5.3 获取1分钟之前的时间
- 5.4 获取1小时之前的时间
- 5.5 获取1分钟之后的时间
- 5.6 获取1小时之后的时间
- 5.7 计算两个时间戳之间的时间
- 5.8 判断一个时间是否在一个时间之后
- 5.9 判断一个时间相比另外一个时间过去了多久
- 6 time.Sleep睡眠指定时间(小时级到纳秒级)
- 6.1 单位
- 6.2 转换单位
- 7 耗时统计
- 7.1 常规写法
- 7.2 原始方式
- 7.3 简洁方法
- 7.4 优雅方法
- 总结
currentTime:=time.Now() //获取当前时间,类型是Go的时间类型Time
t1:=time.Now().Year() //年
t2:=time.Now().Month() //月
t3:=time.Now().Day() //日
t4:=time.Now().Hour() //小时
t5:=time.Now().Minute() //分钟
t6:=time.Now().Second() //秒
t7:=time.Now().Nanosecond() //纳秒
//如果获取UTC时间,则可以使用time.UTCcurrentTimeData:=time.Date(t1,t2,t3,t4,t5,t6,t7,time.Local) //获取当前时间,返回当前时间Time
fmt.Println(currentTime) //打印结果:2017-04-11 12:52:52.794351777 +0800 CST
fmt.Println(t1,t2,t3,t4,t5,t6) //打印结果:2017 April 11 12 52 52
fmt.Println(currentTimeData) //打印结果:2017-04-11 12:52:52.794411287 +0800 CST
time.Now()和Date()方法都可以获取当前时间,time.Now()用起来比较简单,但是Date()可以获取不同的精确值,如time.Date(t1,t2,t3,t4,t5,t6,0,time.Local)将毫秒省略,精确到秒,结果为:2017-04-11 12:52:52 +0800 CST。
timeUnix:=time.Now().Unix() //单位s,打印结果:1491888244
timeUnixNano:=time.Now().UnixNano() //单位纳秒,打印结果:1491888244752784461
timeStr:=time.Now().Format("2006-01-02 15:04:05") //当前时间的字符串,2006-01-02 15:04:05据说是golang的诞生时间,固定写法
fmt.Println(timeStr) //打印结果:2017-04-11 13:24:04
timeUnix:=time.Now().Unix() //已知的时间戳
formatTimeStr:=time.Unix(timeUnix,0).Format("2006-01-02 15:04:05")
fmt.Println(formatTimeStr) //打印结果:2017-04-11 13:30:39
formatTimeStr="2017-04-11 13:33:37"
formatTime,err:=time.Parse("2006-01-02 15:04:05",formatTimeStr)
if err==nil{
fmt.Println(formatTime) //打印结果:2017-04-11 13:33:37 +0000 UTC
}
formatTimeStr="2017-04-11 13:33:37"
formatTime,err:=time.Parse("2006-01-02 15:04:05",formatTimeStr)
utime := formatTime.Unix()
if err == nil{
fmt.Println(utime) //打印结果:2017-04-11 13:33:37 +0000 UTC
}
currentTime := time.Now()
startTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 0, 0, 0, 0, currentTime.Location())
fmt.Println(startTime)
fmt.Println(startTime.Format("2006/01/02 15:04:05"))
currentTime := time.Now()
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
fmt.Println(endTime)
fmt.Println(endTime.Format("2006/01/02 15:04:05"))
m, _ := time.ParseDuration("-1m")
result := currentTime.Add(m)
fmt.Println(result)
fmt.Println(result.Format("2006/01/02 15:04:05"))
m, _ := time.ParseDuration("-1h")
result := currentTime.Add(m)
fmt.Println(result)
fmt.Println(result.Format("2006/01/02 15:04:05"))
m, _ := time.ParseDuration("1m")
result := currentTime.Add(m)
fmt.Println(result)
fmt.Println(result.Format("2006/01/02 15:04:05"))
m, _ := time.ParseDuration("1h")
result := currentTime.Add(m)
fmt.Println(result)
fmt.Println(result.Format("2006/01/02 15:04:05"))
afterTime, _ := time.ParseDuration("1h")
result := currentTime.Add(afterTime)
beforeTime, _ := time.ParseDuration("-1h")
result2 := currentTime.Add(beforeTime)
m := result.Sub(result2)
fmt.Printf("%v 分钟 n", m.Minutes())
h := result.Sub(result2)
fmt.Printf("%v小时 n", h.Hours())
d := result.Sub(result2)
fmt.Printf("%v 天n", d.Hours()/24)
stringTime, _ := time.Parse("2006-01-02 15:04:05", "2019-12-12 12:00:00")
beforeOrAfter := stringTime.After(time.Now())
if true == beforeOrAfter {
fmt.Println("2019-12-12 12:00:00在当前时间之后!")
} else {
fmt.Println("2019-12-12 12:00:00在当前时间之前!")
}
startTime := time.Now()
time.Sleep(time.Second * 5)
fmt.Println("离现在过去了:", time.Since(startTime))
golang的休眠可以使用time包中的Sleep函数实现,本节主要介绍关于go time.Sleep睡眠指定时间(小时级到纳秒级)相关实现。
time.sleep单位为:1ns (纳秒)
- 1纳秒 =1000皮秒
- 1纳秒 =0.001 微秒
- 1纳秒 =0.000 001毫秒
- 1纳秒 =0.000 000 001秒
go用来指定睡眠时间的函数为time.Sleep,接口为:
// Sleep pauses the current goroutine for at least the duration d. // A negative or zero duration causes Sleep to return immediately. func Sleep(d Duration)
传入的为一个Duration,所以如果想睡眠5s钟,不能直接写 time.Sleep(5) ,而应该写time.Sleep(5 * time.Second)
其中time.Second就是一个Duration类型,表示1s的时间间隔,乘系数5就得到5s的时间间隔。
除了time.Second外,go还提供了不同的时间单位:
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
其中,
- Nanosecond表示1纳秒的时间间隔
- Microsecond表示1微妙的时间间隔
- Millisecond表示1毫秒的时间间隔
- Second表示1秒的时间间隔
- Minute表示1分钟的时间间隔
- Hour表示1小时的时间间隔
想要睡眠的时间可以使用以上的常量自由组合,比如睡眠1小时10分5秒:
time.Sleep(1*time.Hour + 10*time.Minute + 5*time.Second)
package main
import (
"fmt"
"time"
)
func main() {
bT := time.Now() // 开始时间
time.Sleep(5*time.Second)
eT := time.Since(bT) // 从开始到当前所消耗的时间
fmt.Println("Run time: ", eT)
}
运行结果:
Run time: 5.001531s
在函数起始位置计算当前时间,在函数结束位置算出耗时。
package main
import (
"fmt"
"time"
)
func sum(n int) int {
var total int
startT := time.Now()//计算当前时间 total := 0
for i:=1; i <= n; i++ {
total += i
}
tc := time.Since(startT)//计算耗时
fmt.Printf("time cost = %vn", tc)
return total
}
func main() {
count := sum(100)
fmt.Printf("count = %vn", count)
}
运行结果:
time cost = 250ns count = 5050
计算当前时间与计算耗时放在两处,难免显得丑陋,且不易阅读。如果有多个函数需要统计耗时,那么多处书写重复的两行代码会造成代码冗余。由于 Golang 提供了函数延时执行的功能,借助 defer ,可以通过函数封装的方式来避免代码冗余。
package main
import (
"fmt"
"time"
)
//耗时统计函数
func timeCost(start time.Time){
tc:=time.Since(start)
fmt.Printf("time cost = %vn", tc)
}
func sum(n int) int {
defer timeCost(time.Now())
total := 0
for i:=1; i <= n; i++ {
total += i
}
return total
}
func main() {
count := sum(100)
fmt.Printf("count = %vn", count)
}
运行结果:
time cost = 333ns count = 5050
通过输出可以看到sum()耗时增加了,因为增加了一次timeCost()函数调用。不过相比于函数封装带来的便利与代码美观,新增的耗时是微不足道可以接受的。
每次调用耗时统计函数timeCost()都需要传入time.Now(),重复书写time.Now()无疑造成了代码冗余。
在上面的基础上,进行进一步的封装,实现如下:
package main
import (
"fmt"
"time"
)
//耗时统计函数
func timeCost() func() {
start := time.Now()
return func() {
tc:=time.Since(start)
fmt.Printf("time cost = %vn", tc)
}
}
func sum(n int) int {
defer timeCost()()//注意,是对 timeCost()返回的函数进行调用,因此需要加两对小括号
total := 0
for i:=1; i <= n; i++ {
total += i
}
return total
}
func main() {
count := sum(100)
fmt.Printf("count = %vn", count)
}
运行结果:
time cost = 1.204µs count = 5050
以上为个人经验,希望能给大家一个参考,也希望大家多多支持风君子博客。
您可能感兴趣的文章:
- 15个Golang中时间处理的实用函数
- Golang时间处理库go-carbon v2.2.13发布细则
- Go语言时间处理必备技巧全解析
- Golang时间处理中容易踩的坑分析解决
- 详解Golang时间处理的踩坑及解决
- 详解Go 中的时间处理