Jack
Jack

Reputation: 373

how to convert duration to days in Go

In Go, how can I convert duration to number of days?

for eg 1W => 7days, 1Y => 365days etc.

Upvotes: 5

Views: 28446

Answers (2)

twiny
twiny

Reputation: 312

you can try this pkg: https://github.com/hako/durafmt

package main

import (
    "fmt"
    "github.com/hako/durafmt"
)

func main() {
    duration, err := durafmt.ParseString("354h22m3.24s")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(duration) // 2 weeks 18 hours 22 minutes 3 seconds
    // duration.String() // String representation. "2 weeks 18 hours 22 minutes 3 seconds"
}

Upvotes: -1

Jonathan Hall
Jonathan Hall

Reputation: 79516

The short answer, for many common purposes, is just to divide the number of hours by 24, to get a generally useful approximation of the number of days.

d, _ := time.ParseDuration("48h")
days := d.Hours()/24 // 2 days

However, this isn't always "correct", depending on your situation. Consider:

How many days between November 1, 2018 midnight and November 8, 2018 midnight? The answer actually depends on at least two things: Your definition of day, and where you're located. If you calculate the duration between the two dates, and divide as described above, your answer will be 7.04167 days, if you're located in the US, due to the daylight savings change.

If your time period happens at the right time in the spring, your answer might be 6.95833 days, due to the DST change in the other direction.

If you account for multiple timezones, leap seconds, or other aberation from "normal", you can end up with even more confusing results.

For some purposes, 7.04167 days would be the right answer. For other purposes, 7 would be the right answer.

So the first task, when trying to calculate "days" is always to determine what definition matters to you. Then second, figure out how to calculate a meaningful number that satisfies that need.

Upvotes: 17

Related Questions