Created
August 25, 2020 16:32
-
-
Save martinusso/89869de6f30522a047d2274b9cc89155 to your computer and use it in GitHub Desktop.
golang duration in days, months, years...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math" | |
"time" | |
) | |
func RoundTime(input float64) int { | |
var result float64 | |
if input < 0 { | |
result = math.Ceil(input - 0.5) | |
} else { | |
result = math.Floor(input + 0.5) | |
} | |
// only interested in integer, ignore fractional | |
i, _ := math.Modf(result) | |
return int(i) | |
} | |
func main() { | |
past, err := time.Parse("2006-01-02", "1984-09-11") | |
if err != nil { | |
panic(err) | |
} | |
diff := time.Since(past) | |
fmt.Println("Now : ", time.Now()) | |
fmt.Println("Time reach the future date : ", past) | |
fmt.Println("Raw : ", diff) | |
fmt.Println("Hours : ", diff.Hours()) | |
fmt.Println("Minutes : ", diff.Minutes()) | |
fmt.Println("Seconds : ", diff.Seconds()) | |
fmt.Println("Nano seconds : ", diff.Nanoseconds()) | |
// get day, month and year | |
fmt.Println("Days : ", RoundTime(diff.Seconds()/86400)) | |
fmt.Println("Weeks : ", RoundTime(diff.Seconds()/604800)) | |
fmt.Println("Months : ", RoundTime(diff.Seconds()/2600640)) | |
fmt.Println("Years : ", RoundTime(diff.Seconds()/31207680)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Seems to me that number of months can be wrong, since each month has a different length (28/29/30/31) and you use a rounded duration.
Something like this should be exact.