The solution has a bug when b has the year higher than a. In my project I 
use a solution based on the Julian Day. More about this you can read 
here: http://en.wikipedia.org/wiki/Julian_day

On Wednesday, October 21, 2015 at 3:34:51 PM UTC+3, Karthik Krishnamurthy 
wrote:
>
> This is an old post, but responding to it in case someone else needs this.
>
> http://play.golang.org/p/nTcjGZQKAa
>
>
> On Saturday, February 23, 2013 at 2:04:46 PM UTC-8, Vincent wrote:
>>
>> Hi,
>>
>>  I recently needed to compute the difference between to dates, expressed 
>> in days. I assumed this was a common operation - it comes often enough when 
>> manipulating dates - but I couldn't find any trivial go code for this.
>> I came up with the following solution (the only other alternative I 
>> considered so far was to compute the duration between the two dates, divide 
>> the result by 24*time.Hour and then round the result... but somehow I gave 
>> up because it felt somehow ugly - and also because AFAICT there is no 
>> ready-to-use "round a float to the nearest integer" function in the std 
>> library).
>>
>> I'd be curious to know if people here can suggest a better way of doing 
>> this...
>>
>> Best regards,
>>
>> Vincent
>>
>> --------------------------------
>> package main
>>
>> import "fmt"
>> import "time"
>>
>> func diffDays(year2, month2, day2, year1, month1, day1 int) int {
>>     if year2 < year1 {
>>         return -diffDays(year1, month1, day1, year2, month2, day2)
>>     }
>>     d2 := time.Date(year2, time.Month(month2), day2, 0, 0, 0, 0, time.UTC)
>>     d1 := time.Date(year1, time.Month(month1), day1, 0, 0, 0, 0, time.UTC)
>>     diff := d2.YearDay() - d1.YearDay()
>>
>>     for y := year1; y < year2; y++ {
>>         diff += time.Date(y, time.December, 31, 0, 0, 0, 0, 
>> time.UTC).YearDay()
>>     }
>>     /* if debug && !d1.AddDate(0, 0, diff).Equal(d2) {
>>         panic("invalid diff")
>>     } */
>>     return diff
>> }
>>
>> func main() {
>>     d := diffDays(2012, 9, 31, 2011, 10, 1)
>>     fmt.Println(d, " days")
>>
>> }
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to