分享
golang 时间计算
漂泊的树叶 · · 8282 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
package test
import (
"testing"
"time"
"fmt"
)
func Test_time(t *testing.T) {
now := time.Now()
fmt.Println("当前时间:", now)
//两小时之后的时间
h,_ := time.ParseDuration("2h")
nowAfter2Hour := now.Add(h)
fmt.Println("两小时之后的时间:", nowAfter2Hour)
//两小时之前的时间
negativeH,_ := time.ParseDuration("-2h")
nowBefore2Hour := now.Add(negativeH)
fmt.Println("两小时之前的时间:", nowBefore2Hour)
//十分钟之后的时间
m,_ := time.ParseDuration("10m")
nowAfter10Minute := now.Add(m)
fmt.Println("十分钟之后的时间:", nowAfter10Minute)
//十分钟之前的时间
negativeM,_ := time.ParseDuration("-10m")
nowBefore10Minute := now.Add(negativeM)
fmt.Println("十分钟之前的时间:", nowBefore10Minute)
//30s之后的时间
s,_ := time.ParseDuration("30s")
nowAfter30Second := now.Add(s)
fmt.Println("30s之后的时间:", nowAfter30Second)
//30s之前的时间
negativeS,_ := time.ParseDuration("-30s")
nowBefore30Second := now.Add(negativeS)
fmt.Println("30s之前的时间:", nowBefore30Second)
//1年1个月1天 之后的时间
fmt.Println("1年2个月3天之后的时间:", now.AddDate(1, 2, 3))
//2年2个月2天之前的时间
fmt.Println("2年3个月4天之前的时间:", now.AddDate(-2, -3, -4))
}
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信8282 次点击
上一篇:golang开发目录结构
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
package test
import (
"testing"
"time"
"fmt"
)
func Test_time(t *testing.T) {
now := time.Now()
fmt.Println("当前时间:", now)
//两小时之后的时间
h,_ := time.ParseDuration("2h")
nowAfter2Hour := now.Add(h)
fmt.Println("两小时之后的时间:", nowAfter2Hour)
//两小时之前的时间
negativeH,_ := time.ParseDuration("-2h")
nowBefore2Hour := now.Add(negativeH)
fmt.Println("两小时之前的时间:", nowBefore2Hour)
//十分钟之后的时间
m,_ := time.ParseDuration("10m")
nowAfter10Minute := now.Add(m)
fmt.Println("十分钟之后的时间:", nowAfter10Minute)
//十分钟之前的时间
negativeM,_ := time.ParseDuration("-10m")
nowBefore10Minute := now.Add(negativeM)
fmt.Println("十分钟之前的时间:", nowBefore10Minute)
//30s之后的时间
s,_ := time.ParseDuration("30s")
nowAfter30Second := now.Add(s)
fmt.Println("30s之后的时间:", nowAfter30Second)
//30s之前的时间
negativeS,_ := time.ParseDuration("-30s")
nowBefore30Second := now.Add(negativeS)
fmt.Println("30s之前的时间:", nowBefore30Second)
//1年1个月1天 之后的时间
fmt.Println("1年2个月3天之后的时间:", now.AddDate(1, 2, 3))
//2年2个月2天之前的时间
fmt.Println("2年3个月4天之前的时间:", now.AddDate(-2, -3, -4))
}