Home > Net >  golang conditionals on the time difference (sub)
golang conditionals on the time difference (sub)

Time:10-29

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 <= 5m {
   do this
}
if diff > 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.

CodePudding user response:

You can simply use the comparison operators, for example:

d, _ := time.ParseDuration("4m4s")
if d <= 5 * time.Second {
    fmt.Println("<= than limit")
} else {
    fmt.Println("> than limit")
}

CodePudding user response:

On the parser side, you have a library like hmoragrega/after able to parse a time unit and a signed multiplier (emulating the time.ParseDuration from arif's answer)

parser := after.New()

// "Duration" returns a time.Duration object with the equivalent of the input
anHour, err := parser.Duration("1 hour")

// SinceNow returns a time.Time object that represents the current point in time plus (or minus) the specified duration
inTenMinutes, err := parser.SinceNow("10 minutes")

// "Since" returns a time.Time object that represents the given point in time plus the specified input
nowAgain, err := parser.Since(inTenMinutes, "-10 minutes")

CodePudding user response:

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("\nIn just minites: %.f\n", timeDiff.Minutes())

Playground

If we would have the "difference" as a string ("10m2s") 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 = "10h10m6s"
timeDiff, _ := time.ParseDuration(t)
numberOfHours := timeDiff.Hours()
numberOfMinutes := timeDiff.Minutes()
numberOfSeconds := timeDiff.Seconds()
numberofNanosec := timeDiff.Nanoseconds()

Find the example snippet on the playground

So in any of the above cases, we can use time.Minutes() to compare the duration. Something like the following,

if timeDiff.Mintues() < 5 {
   do something
} else if timeDiff.Minitues() > 5 {
   do something else
} else {
   do nothing
}

An example is on the playground.

  •  Tags:  
  • go
  • Related