计算两个日期之间的差值,以年、天、小时、分钟等单位。

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

Calculating deltas between two dates in years, days, hours, mins etc

问题

我正在处理一个需要进行一些日期计算的 Golang 示例。我原本希望 Go 提供一些类似于 Python 中优秀的 datetime 模块的好用日期库,但事实并非如此。

你想知道如何在 Go 中表示这个 Python 示例吗?

package main

import (
	"fmt"
	"time"
)

func main() {
	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)
}

这段代码将输出 -1865,与 Python 示例中的结果相同。

我花了很多时间搜索如何在 Go 中进行日期计算,但似乎找不到一个明确、简洁且没有诸如不正确计算闰年等限制的答案。

这似乎是一个相当大的限制,对于一个正在成为一个出色的跨平台原型构建和最终生产应用的语言来说。

英文:

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

得分: 2

我不知道你花了多少时间寻找却找不到任何东西,但标准库的time包中有你想要的一切。

以下是你用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)

输出结果(如预期):

-1865

你可以在Go Playground上尝试运行它。

英文:

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.

huangapple
  • 本文由 发表于 2015年4月2日 17:49:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/29409908.html
匿名

发表评论

匿名网友

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

确定