How can I calculate the number of days between two dates? In the code below I should get the number of hours, which means that I should only need to divide by 24. However, the result I get is something like -44929.000000. I'm only looking a day or two back so I would expect 24 or 48 hours.
package main import ( "fmt" "time" ) func main() { timeFormat := "2006-01-02" t, _ := time.Parse(timeFormat, "2014-12-28") fmt.Println(t) // duration := time.Since(t) duration := time.Now().Sub(t) fmt.Printf("%f", duration.Hours()) }
Here's the executable Go code: http://play.golang.org/p/1MV6wnLVKh
To calculate the number of days between two dates, you need to subtract the start date from the end date. If this crosses several years, you should calculate the number of full years. For the period left over, work out the number of months. For the leftover period, work out the number of days.
Your program seems to work as intended. I'm getting 45.55 hours. Have you tried to run it locally?
Playground time is fixed, time.Now() will give you 2009-11-10 23:00:00 +0000 UTC always.
package main import ( "fmt" "time" ) func main() { date := time.Now() fmt.Println(date) format := "2006-01-02 15:04:05" then,_ := time.Parse(format, "2007-09-18 11:58:06") fmt.Println(then) diff := date.Sub(then) //func Since(t Time) Duration //Since returns the time elapsed since t. //It is shorthand for time.Now().Sub(t). fmt.Println(diff.Hours())// number of Hours fmt.Println(diff.Nanoseconds())// number of Nanoseconds fmt.Println(diff.Minutes())// number of Minutes fmt.Println(diff.Seconds())// number of Seconds fmt.Println(int(diff.Hours()/24))// number of days }
Here is the running code https://play.golang.org/p/Vbhh1cBKnh
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With