计算两个日期之间的天数?

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

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

the below code gives the list of all the days along with the number of days between the from date and to date: you can click on the link for the code in Go PlayGround:https://play.golang.org/p/MBThBpTqjdz

to := time.Now()
from := to.AddDate(0, -1, 0)
fmt.Println("toDate", to)
fmt.Println("fromDate", from)
days := to.Sub(from) / (24 * time.Hour)
fmt.Println("days", int(days))
noofdays := int(days)

for i := 0; i <= noofdays; i++ {
    fmt.Println(from.AddDate(0, 0, i))
}

One caveat to be mindful of when using this technique of timeOne.Sub(timeTwo).Hours() / 24 is that daylights savings can cause a day to contain only 23 hours, throwing this calculation off slightly.