两个time.Time对象之间的时差 [英] Difference between two time.Time objects

查看:62
本文介绍了两个time.Time对象之间的时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go的新功能。问题可能是基本的。

Very new to the 'Go'. Question might be basic one.

我有两个time.Time对象,我想获取两者之间在小时/分钟/秒方面的差异。可以说:

I have two time.Time objects and I want to get the difference between the two in terms of hours/minutes/seconds. Lets say:

t1 = 2016-09-09 19:09:16 +0530 IST
t2 = 2016-09-09 19:09:16 +0530 IST

在上述情况下,由于差异为0。它应该给我00:00:00。考虑另一种情况:

In above case, since the difference is 0. It should give me 00:00:00. Consider another case:

t1 = 2016-09-14 14:12:48 +0530 IST
t2 = 2016-09-14 14:18:29 +0530 IST

在这种情况下,差值为00: 05:41。我查看了 https://godoc.org/time ,但无法从中获得任何好处。

In this case, difference would be 00:05:41. I looked at the https://godoc.org/time but could not make anything out of it.

推荐答案

您可以使用 Time.Sub() 来获取2个 time.Time 值,结果将是 time.Duration

You may use Time.Sub() to get the difference between the 2 time.Time values, result will be a value of time.Duration.

打印时, time.Duration 会智能格式化自身:

When printed, a time.Duration formats itself "intelligently":

t1 := time.Now()
t2 := t1.Add(time.Second * 341)

fmt.Println(t1)
fmt.Println(t2)

diff := t2.Sub(t1)
fmt.Println(diff)

输出:

2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:05:41 +0000 UTC
5m41s

如果你想t时间格式 HH:mm:ss ,您可以构造 time.Time 值并使用其 Time.Format() 方法:

If you want the time format HH:mm:ss, you may constuct a time.Time value and use its Time.Format() method like this:

out := time.Time{}.Add(diff)
fmt.Println(out.Format("15:04:05"))

输出:

00:05:41

尝试去游乐场上的示例。

当然,这仅在时差少于一天的情况下有效。如果差异可能更大,那就另当别论了。结果必须包括几天,几个月和几年。复杂性显着增加。有关详细信息,请参见此问题:

Of course this will only work if the time difference is less than a day. If the difference may be bigger, then it's another story. The result must include days, months and years. Complexity increases significnatly. See this question for details:

golang时间。Since()具有年份和年份

此处显示的解决方案通过显示带有签名的函数来解决此问题:

The solution presented there solves this issue by showing a function with signature:

func diff(a, b time.Time) (year, month, day, hour, min, sec int)

即使您的时间在24小时以内(在这种情况下,年),您也可以使用它将为 0 )。

You may use that even if your times are within 24 hours (in which case year, month and day will be 0).

这篇关于两个time.Time对象之间的时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆