在Golang中,可以使用条件语句来比较时间差异(减法)。

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

golang conditionals on the time difference (sub)

问题

我有两个时间,t1t2
要计算差异,我使用以下代码:

diff := t2.sub(t1)

上述代码返回类似于10m30s1h3m59s等的差异。

我需要为差异创建一些条件。
例如,

if diff <= 5m {
   做这个
}
if diff > 20m {
   做那个
}

我的问题是是否有内置的方法来比较时间差异。

我的另一个选择是使用正则表达式解析返回的差异,然后进行比较。但我希望能找到一些像时间包提供的sub这样高效的方法。

英文:

I have two times, t1 and t2.
To calculate the difference, I use,

diff := t2.sub(t1)

The above code returns the difference like 10m30s, 1h3m59s etc.

I need to create some conditions for the difference.
For example,

if diff &lt;= 5m {
   do this
}
if diff &gt; 20m {
   do that
}

My question is if there is any built-in way to compare the time difference.

My other option would be to parse returned diff with regex and then compare. But I was looking for some efficient ways like the sub which the time package offers.

答案1

得分: 3

t2.Sub(t1) 返回一个时间间隔,你可以直接使用比较运算符,例如:

d, _ := time.ParseDuration("4m4s")
if d <= 5 * time.Second {
    fmt.Println("小于等于限制")
} else {
    fmt.Println("大于限制")
}
英文:

t2.Sub(t1) returns a duration, and you can simply use the comparison operators, for example:

d, _ := time.ParseDuration(&quot;4m4s&quot;)
if d &lt;= 5 * time.Second {
	fmt.Println(&quot;&lt;= than limit&quot;)
} else {
	fmt.Println(&quot;&gt; than limit&quot;)
}

答案2

得分: 2

方式1: 使用sub函数获取持续时间时

一个非常简单的替代方法是直接使用sub函数的输出。sub函数返回time.Duration类型。因此,只需在其后添加.Minutes()方法即可满足我的需求。

t1 := time.Now()
time.Sleep(60011 * time.Millisecond)
t2 := time.Now()
timeDiff := t2.Sub(t1)
fmt.Println(timeDiff)
fmt.Printf("\nIn just minites: %.f\n", timeDiff.Minutes())

Playground

方式2: 当我们有一个以string形式表示的持续时间时

如果我们将"差异"表示为string类型("10m2s"),我认为我们需要使用ParseDuration函数。从godocs中了解到ParseDuration
从文档中可以看到,

ParseDuration解析持续时间字符串。持续时间字符串是一系列可能带有小数部分和单位后缀的有符号十进制数,例如"300ms"、"-1.5h"或"2h45m"。有效的时间单位有"ns"、"us"(或"μs")、"ms"、"s"、"m"、"h"。

我考虑使用以下方式:

t := "10h10m6s"
timeDiff, _ := time.ParseDuration(t)
numberOfHours := timeDiff.Hours()
numberOfMinutes := timeDiff.Minutes()
numberOfSeconds := timeDiff.Seconds()
numberofNanosec := timeDiff.Nanoseconds()

playground上找到示例代码片段

<strike>因此,在上述任何一种情况下,我们都可以使用time.Minutes()来比较持续时间。</strike>正如@gopher指出的那样,为了与任何时间范围进行比较,我们不需要将其转换为任何时间段(例如Minutes()Seconds()),而是可以直接与所需的时间段进行比较。正如@Haris Osmanagić指出的那样,这适用于ParseDurationtime.Sub()的输出,因为它们都返回time.Duration类型。因此,我们可以像下面这样做:

if timeDiff < 5 * time.Minutes() {
   do something
} else if timeDiff > 5 * time.Minutes(){
   do something else
} else {
   do nothing
}

playground上有一个示例。

英文:

Way 1: When we use sub to get the duration

A very simple alternative is to directly use the output of the sub function. The func sub returns time.Duration type. So just adding .Minutes() method with it would serve the purpose in my case.

	t1 := time.Now()
	time.Sleep(60011 * time.Millisecond)
	t2 := time.Now()
	timeDiff := t2.Sub(t1)
	fmt.Println(timeDiff)
	fmt.Printf(&quot;\nIn just minites: %.f\n&quot;, timeDiff.Minutes())

Playground

Way 2: When we have the duration in string

If we would have the "difference" as a string (&quot;10m2s&quot;) type then I believe we need to use the ParseDuration function. From the godocs ParseDuration
From the doc,

> ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

I am thinking of using it like the following,

t = &quot;10h10m6s&quot;
timeDiff, _ := time.ParseDuration(t)
numberOfHours := timeDiff.Hours()
numberOfMinutes := timeDiff.Minutes()
numberOfSeconds := timeDiff.Seconds()
numberofNanosec := timeDiff.Nanoseconds()

Find the example snippet on the playground

<strike>So in any of the above cases, we can use time.Minutes() to compare the duration.</strike>. As @gopher pointed out that to compare with any time range we do not need to convert it to any period of time (e,g Mintues(), Seconds()) but we can just compare with a required time period. As @Haris Osmanagić pointed out that this works for both of the output of ParseDuration and time.Sub() as they both returns time.Duration type. So we can do something like the following,

if timeDiff &lt; 5 * time.Minutes() {
   do something
} else if timeDiff &gt; 5 * time.Minutes(){
   do something else
} else {
   do nothing
}

An example is on the playground.

huangapple
  • 本文由 发表于 2021年10月29日 13:09:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/69763902.html
匿名

发表评论

匿名网友

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

确定