dongrao9454 2015-04-02 09:49 采纳率: 100%
浏览 140
已采纳

计算年,天,小时,分钟等两个日期之间的差异

I'm working on a Golang example that requires some date calculations. I was rather hoping that Go would provide some nice date libraries similar to the excellent Python datetime module, but that doesn't appear to be the case.

How can I represent this python example in Go ?

from datetime import date

d0 = date(2013, 8, 18)
d1 = date(2018, 9, 26)
delta = d0 - d1
print delta.days
>>-1865

I've spent a fair bit of time looking around on how to do this I can't seem to find a definitive answer that is clear and concise and without caveats such as not properly calculating leap years etc.

This seems to be a fairly big limitation to what is becoming an excellent little language for building cross platform prototypes and eventually production applications.

  • 写回答

1条回答 默认 最新

  • dqprf0976 2015-04-02 09:56
    关注

    I don't know how you've spent your fair bit of time looking and not finding anything, but the time package of the standard library has everything you want.

    Here is your example coded in Go:

    d0 := time.Date(2013, 8, 18, 0, 0, 0, 0, time.UTC)
    d1 := time.Date(2018, 9, 26, 0, 0, 0, 0, time.UTC)
    
    delta := d0.Sub(d1)
    
    fmt.Println(delta.Hours() / 24)
    

    Output (as expected):

    -1865
    

    Try it on the Go Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗