Date difference

How can get a difference of date in golang which has string format “20052010” (20 May 2010)

Take a look at https://gobyexample.com/time-formatting-parsing to see how to parse “20052010” in Go.

Then you can either get the difference between that time and now with time.Since(theYouParsedVariable) or you could get the difference between two parsed dates by using difference := firstParsedDate.Sub(secondParsedDate).

See https://golang.org/pkg/time/#Time.Sub https://golang.org/pkg/time/#Time.Since
Both time.Since and time.Sub return a Duration
Note that time.Since(someOtherTime) is just a shortcut for doing time.Now().Sub(someOtherTime) as you can see here https://golang.org/src/time/time.go?s=28315:28342#L900 :slight_smile:

I may be wrong, but seems your question is geared towards formatting the string (your example is “20052010”).

Golang uses a paradigm date (Mon Jan 2 15:04:05 -0700 MST 2006) for you to parse a time.Time . This date, if you take a closer look, translates to 1(month) 2 (day) 3(hour) 4(minutes) 5 (seconds) 6(year) 7 (time zone). Use this date, in the format you will use, as a layout.

Say you will receive a date in the following format: “15-08-2014” (my daughters birthday). You can create a time.Time instance in the following way:

timeInstance , _ := time.Parse(“02-01-2006”, “15-08-2014”)

Example here at:

https://play.golang.org/p/KrBiVbvc43G

Not sure it helped.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.