douliu1092 2014-04-20 16:05
浏览 29
已采纳

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

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条回答 默认 最新

  • duanbeng8872 2014-04-20 16:41
    关注

    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())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏