创建持续时间或未来日期的惯用方式

huangapple go评论86阅读模式
英文:

Idiomatic way of creating duration or future date

问题

获取两个日期之间的持续时间或基于当前日期获取未来日期的惯用方法是什么?目前,我正在使用以下代码来实现这一目标。

yearSpan := time.Date(time.Now().Year()-1, time.Now().Month(), 
time.Now().Day(), time.Now().Hour(), time.Now().Minute(), time.Now().Second(), 
time.Now().Nanosecond(), time.UTC)

yearDuration := time.Now().Sub(yearSpan)

header.Add("Expires", time.Now().Add(futureDate).String())

我已经在书籍和网站上搜索了很多地方,但是我找不到任何创建持续时间的惯用方法。有没有关于如何以更好的方式重构上述代码的想法?

谢谢

英文:

What would be the idiomatic way of getting a duration between two dates or basically getting a future date based on the current. Right now I'm using the below code to achieve that.

yearSpan := time.Date(time.Now().Year()-1, time.Now().Month(), 
time.Now().Day(), time.Now().Hour(), time.Now().Minute(), time.Now().Second(), 
time.Now().Nanosecond(), time.UTC)

yearDuration := time.Now().Sub(yearSpan)

header.Add("Expires", time.Now().Add(futureDate).String())

I've pretty much looked everywhere in books and sites but I couldn't find any idiomatic way creating a duration. Any thoughts on how to refactor the above code in a better way?

Thanks

答案1

得分: 1

time.Duration 被定义为 type Duration int64,所以基本上你只需要进行基本的数学运算就可以得到你想要的持续时间。

例如(在这里试玩):

package main

import (
	"fmt"
	"time"
)

const avgYear = time.Hour * 24 * 365

func main() {
	fmt.Println("Hello, playground")
	fmt.Println("Now", time.Now().String())
	fmt.Println("Last Year", time.Now().Add(-avgYear).String())
	fmt.Println("Next Year", time.Now().Add(avgYear).String())
}
英文:

time.Duration is defined as type Duration int64, so basicly you just do basic math to get the duration you want.

For example (Play with it) :

package main

import (
	"fmt"
	"time"
)

const avgYear = time.Hour * 24 * 365

func main() {
	fmt.Println("Hello, playground")
	fmt.Println("Now", time.Now().String())
	fmt.Println("Last Year", time.Now().Add(-avgYear).String())
	fmt.Println("Next Year", time.Now().Add(avgYear).String())
}

huangapple
  • 本文由 发表于 2014年4月21日 00:05:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/23184583.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定