Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate number of days between two dates?

Tags:

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

like image 704
h4labs Avatar asked Dec 29 '14 21:12

h4labs


People also ask

How do you calculate days between two dates?

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.


2 Answers

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.

like image 166
siritinga Avatar answered Sep 22 '22 15:09

siritinga


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

like image 33
Nisal Edu Avatar answered Sep 22 '22 15:09

Nisal Edu