Golang basic examples of Date and Time manipulation functions

1) How to get the current date and time with timestamp in local and other timezones ?

LoadLocation returns the Location with the given name.

Syntax:
func LoadLocation(name string) (*Location, error)
Example:
package main
import (
	"fmt"
	"time"
)
func main() {
	t := time.Now()
	fmt.Println("Location : ", t.Location(), " Time : ", t) // local time
	location, err := time.LoadLocation("America/New_York")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Location : ", location, " Time : ", t.In(location)) // America/New_York
	loc, _ := time.LoadLocation("Asia/Shanghai")
	now := time.Now().In(loc)
	fmt.Println("Location : ", loc, " Time : ", now) // Asia/Shanghai
}
When you run the program, you get the following output:
C:\golang\time>go run t1.go Location : Local Time : 2017-08-26 21:04:56.1874497 +0530 IST Location : America/New_York Time : 2017-08-26 11:34:56.1874497 -0400 EDT Location : Asia/Shanghai Time : 2017-08-26 23:34:56.1884498 +0800 CST C:\golang\time>

2) Golang Get current Date and Time in EST, UTC and MST

Example:
package main
import (
         "fmt"
         "time"
)
func main() {
	t := time.Now()	
	z, _ := t.Zone()
    fmt.Println("ZONE : ", z, " Time : ", t) // local time
    location, err := time.LoadLocation("EST")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("ZONE : ", location, " Time : ", t.In(location)) // EST
    loc, _ := time.LoadLocation("UTC")
    now := time.Now().In(loc)
    fmt.Println("ZONE : ", loc, " Time : ", now) // UTC	
	loc, _ = time.LoadLocation("MST")
    now = time.Now().In(loc)
    fmt.Println("ZONE : ", loc, " Time : ", now) // MST
}
When you run the program, you get the following output:
C:\golang\time>go run t1.go ZONE : IST Time : 2017-08-26 22:12:31.3763932 +0530 IST ZONE : EST Time : 2017-08-26 11:42:31.3763932 -0500 EST ZONE : UTC Time : 2017-08-26 16:42:31.3773933 +0000 UTC ZONE : MST Time : 2017-08-26 09:42:31.3783934 -0700 MST C:\golang\time>

3) Get Hours, Days, Minutes and Seconds difference between two dates [Future and Past]

Example:
package main
import (
         "fmt"
         "time"
)
func main() {
loc, _ := time.LoadLocation("UTC")
now := time.Now().In(loc)
fmt.Println("\nToday : ", loc, " Time : ", now)
pastDate := time.Date(2015, time.May, 21, 23, 10, 52, 211, time.UTC)
fmt.Println("\n\nPast  : ", loc, " Time : ", pastDate) // 
fmt.Printf("###############################################################\n")
diff := now.Sub(pastDate)
hrs := int(diff.Hours())
fmt.Printf("Diffrence in Hours : %d Hours\n", hrs)
mins := int(diff.Minutes())
fmt.Printf("Diffrence in Minutes : %d Minutes\n", mins)
second := int(diff.Seconds())
fmt.Printf("Diffrence in Seconds : %d Seconds\n", second)
days := int(diff.Hours() / 24)
fmt.Printf("Diffrence in days : %d days\n", days)
fmt.Printf("###############################################################\n\n\n")
futureDate := time.Date(2019, time.May, 21, 23, 10, 52, 211, time.UTC)
fmt.Println("Future  : ", loc, " Time : ", futureDate) // 
fmt.Printf("###############################################################\n")
diff = futureDate.Sub(now)
hrs = int(diff.Hours())
fmt.Printf("Diffrence in Hours : %d Hours\n", hrs)
mins = int(diff.Minutes())
fmt.Printf("Diffrence in Minutes : %d Minutes\n", mins)
second = int(diff.Seconds())
fmt.Printf("Diffrence in Seconds : %d Seconds\n", second)
days = int(diff.Hours() / 24)
fmt.Printf("Diffrence in days : %d days\n", days)
}
When you run the program, you get the following output:
C:\golang\time>go run t3.go Today : UTC Time : 2017-08-27 05:15:53.7106215 +0000 UTC Past : UTC Time : 2015-05-21 23:10:52.000000211 +0000 UTC ############################################################### Diffrence in Hours : 19878 Hours Diffrence in Minutes : 1192685 Minutes Diffrence in Seconds : 71561101 Seconds Diffrence in days : 828 days ############################################################### Future : UTC Time : 2019-05-21 23:10:52.000000211 +0000 UTC ############################################################### Diffrence in Hours : 15185 Hours Diffrence in Minutes : 911154 Minutes Diffrence in Seconds : 54669298 Seconds Diffrence in days : 632 days C:\golang\time>

4) Add N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current datetime.

In below example AddDate and Add function used from Golang Time package.

Syntax:
func (t Time) AddDate(years int, months int, days int) Time
func (t Time) Add(d Duration) Time
Example:
package main
import (
    "fmt"
    "time"
)
func main() {
    now := time.Now()
    fmt.Println("\nToday:", now)
    after := now.AddDate(1, 0, 0)
    fmt.Println("\nAdd 1 Year:", after)
	after = now.AddDate(0, 1, 0)
    fmt.Println("\nAdd 1 Month:", after)
	after = now.AddDate(0, 0, 1)
    fmt.Println("\nAdd 1 Day:", after)
	after = now.AddDate(2, 2, 5)
    fmt.Println("\nAdd multiple values:", after)
	after = now.Add(10*time.Minute)
    fmt.Println("\nAdd 10 Minutes:", after)
	after = now.Add(10*time.Second)
    fmt.Println("\nAdd 10 Second:", after)
	after = now.Add(10*time.Hour)
    fmt.Println("\nAdd 10 Hour:", after)
	after = now.Add(10*time.Millisecond)
    fmt.Println("\nAdd 10 Millisecond:", after)
	after = now.Add(10*time.Microsecond)
    fmt.Println("\nAdd 10 Microsecond:", after)
	after = now.Add(10*time.Nanosecond)
    fmt.Println("\nAdd 10 Nanosecond:", after)
}
When you run the program, you get the following output:
C:\golang\time>go run t4.go Today: 2017-08-27 11:17:54.1224628 +0530 IST Add 1 Year: 2018-08-27 11:17:54.1224628 +0530 IST Add 1 Month: 2017-09-27 11:17:54.1224628 +0530 IST Add 1 Day: 2017-08-28 11:17:54.1224628 +0530 IST Add multiple values: 2019-11-01 11:17:54.1224628 +0530 IST Add 10 Minutes: 2017-08-27 11:27:54.1224628 +0530 IST Add 10 Second: 2017-08-27 11:18:04.1224628 +0530 IST Add 10 Hour: 2017-08-27 21:17:54.1224628 +0530 IST Add 10 Millisecond: 2017-08-27 11:17:54.1324628 +0530 IST Add 10 Microsecond: 2017-08-27 11:17:54.1224728 +0530 IST Add 10 Nanosecond: 2017-08-27 11:17:54.12246281 +0530 IST C:\golang\time>

5) Subtract N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current datetime.

In below example AddDate and Add function used from Golang Time package.

Syntax:
func (t Time) AddDate(years int, months int, days int) Time
func (t Time) Add(d Duration) Time
Example:
package main
import (
    "fmt"
    "time"
)
func main() {
    now := time.Now()
    fmt.Println("Today:", now)
    after := now.AddDate(-1, 0, 0)
    fmt.Println("Subtract 1 Year:", after)
	after = now.AddDate(0, -1, 0)
    fmt.Println("Subtract 1 Month:", after)
	after = now.AddDate(0, 0, -1)
    fmt.Println("Subtract 1 Day:", after)
	after = now.AddDate(-2, -2, -5)
    fmt.Println("Subtract multiple values:", after)
	after = now.Add(-10*time.Minute)
    fmt.Println("Subtract 10 Minutes:", after)
	after = now.Add(-10*time.Second)
    fmt.Println("Subtract 10 Second:", after)
	after = now.Add(-10*time.Hour)
    fmt.Println("Subtract 10 Hour:", after)
	after = now.Add(-10*time.Millisecond)
    fmt.Println("Subtract 10 Millisecond:", after)
	after = now.Add(-10*time.Microsecond)
    fmt.Println("Subtract 10 Microsecond:", after)
	after = now.Add(-10*time.Nanosecond)
    fmt.Println("Subtract 10 Nanosecond:", after)
}
When you run the program, you get the following output:
C:\golang\time>go run t5.go Today: 2017-08-27 12:21:17.8379942 +0530 IST Subtract 1 Year: 2016-08-27 12:21:17.8379942 +0530 IST Subtract 1 Month: 2017-07-27 12:21:17.8379942 +0530 IST Subtract 1 Day: 2017-08-26 12:21:17.8379942 +0530 IST Subtract multiple values: 2015-06-22 12:21:17.8379942 +0530 IST Subtract 10 Minutes: 2017-08-27 12:11:17.8379942 +0530 IST Subtract 10 Second: 2017-08-27 12:21:07.8379942 +0530 IST Subtract 10 Hour: 2017-08-27 02:21:17.8379942 +0530 IST Subtract 10 Millisecond: 2017-08-27 12:21:17.8279942 +0530 IST Subtract 10 Microsecond: 2017-08-27 12:21:17.8379842 +0530 IST Subtract 10 Nanosecond: 2017-08-27 12:21:17.83799419 +0530 IST C:\golang\time>

6) Get current date and time in various format in golang.

Example:
package main
import (
    "fmt"
    "time"
)
func main() {
    currentTime := time.Now()
    fmt.Println("Current Time in String: ", currentTime.String())
    fmt.Println("MM-DD-YYYY : ", currentTime.Format("01-02-2006"))
    fmt.Println("YYYY-MM-DD : ", currentTime.Format("2006-01-02"))
	fmt.Println("YYYY.MM.DD : ", currentTime.Format("2006.01.02 15:04:05"))
	fmt.Println("YYYY#MM#DD {Special Character} : ", currentTime.Format("2006#01#02"))
    fmt.Println("YYYY-MM-DD hh:mm:ss : ", currentTime.Format("2006-01-02 15:04:05"))
    fmt.Println("Time with MicroSeconds: ", currentTime.Format("2006-01-02 15:04:05.000000"))
    fmt.Println("Time with NanoSeconds: ", currentTime.Format("2006-01-02 15:04:05.000000000"))
	fmt.Println("ShortNum Month : ", currentTime.Format("2006-1-02"))
	fmt.Println("LongMonth : ", currentTime.Format("2006-January-02"))
	fmt.Println("ShortMonth : ", currentTime.Format("2006-Jan-02"))
	fmt.Println("ShortYear : ", currentTime.Format("06-Jan-02"))
	fmt.Println("LongWeekDay : ", currentTime.Format("2006-01-02 15:04:05 Monday"))
	fmt.Println("ShortWeek Day : ", currentTime.Format("2006-01-02 Mon"))	
	fmt.Println("ShortDay : ", currentTime.Format("Mon 2006-01-2"))
	fmt.Println("Short Hour Minute Second: ", currentTime.Format("2006-01-02 3:4:5"))	
	fmt.Println("Short Hour Minute Second: ", currentTime.Format("2006-01-02 3:4:5 PM"))	
	fmt.Println("Short Hour Minute Second: ", currentTime.Format("2006-01-02 3:4:5 pm"))	
}
When you run the program, you get the following output:
C:\golang\time>go run t6.go Current Time in String: 2017-07-04 00:47:20.1424751 +0530 IST MM-DD-YYYY : 07-04-2017 YYYY-MM-DD : 2017-07-04 YYYY.MM.DD : 2017.07.04 00:47:20 YYYY#MM#DD {Special Character} : 2017#07#04 YYYY-MM-DD hh:mm:ss : 2017-07-04 00:47:20 Time with MicroSeconds: 2017-07-04 00:47:20.142475 Time with NanoSeconds: 2017-07-04 00:47:20.142475100 ShortNum Month : 2017-7-04 LongMonth : 2017-July-04 ShortMonth : 2017-Jul-04 ShortYear : 17-Jul-04 LongWeekDay : 2017-07-04 00:47:20 Tuesday ShortWeek Day : 2017-07-04 Tue ShortDay : Tue 2017-07-4 Short Hour Minute Second: 2017-07-04 12:47:20 Short Hour Minute Second: 2017-07-04 12:47:20 AM Short Hour Minute Second: 2017-07-04 12:47:20 am C:\golang\time>

7) Get Year, Month, Day, Hour, Min and Second from current date and time.

Below program use Parse function to get Year, Month, Day, Hour, Min and Second from current date and time. The Clock function used to returns the hour, minute, and second within the day specified by time T.

Example:
package main
 import (
         "fmt"
         "time"		 
 )
 func main() {		 
	currentTime := time.Now()		 
	fmt.Println("\n######################################\n")
	fmt.Println(currentTime.Format("2006-01-02 15:04:05"))
	fmt.Println("\n######################################\n")	
	timeStampString := currentTime.Format("2006-01-02 15:04:05")	
    layOut := "2006-01-02 15:04:05"		 
    timeStamp, err := time.Parse(layOut, timeStampString)
    if err != nil {
        fmt.Println(err)          
    }	
	hr, min, sec := timeStamp.Clock()
	fmt.Println("Year	:", currentTime.Year())
	fmt.Println("Month	:", currentTime.Month())
	fmt.Println("Day	:", currentTime.Day())
	fmt.Println("Hour	:", hr)
	fmt.Println("Min	:", min)
	fmt.Println("Sec	:", sec)	
	fmt.Println("\n######################################\n")	
	year, month, day := time.Now().Date()
	fmt.Println("Year 	:", year)
	fmt.Println("Month	:", month)
	fmt.Println("Day	:", day)
	fmt.Println("\n######################################\n")		   
	t := time.Now()
	y := t.Year()
	mon := t.Month()
	d := t.Day()
	h := t.Hour()
	m := t.Minute()
	s := t.Second()
	n := t.Nanosecond()
	fmt.Println("Year   :",y)
	fmt.Println("Month   :",mon)
	fmt.Println("Day   :",d)
	fmt.Println("Hour   :",h)
	fmt.Println("Minute :",m)
	fmt.Println("Second :",s)
	fmt.Println("Nanosec:",n)
}
When you run the program, you get the following output:
C:\golang\time>go run t7.go ###################################### 2017-08-27 18:11:54 ###################################### Year : 2017 Month : August Day : 27 Hour : 18 Min : 11 Sec : 54 ###################################### Year : 2017 Month : August Day : 27 ###################################### Year : 2017 Month : August Day : 27 Hour : 18 Minute : 11 Second : 54 Nanosec: 319513100 C:\golang\time>

8) Get Year, Month, Day, Hour, Min and Second from a specified date.

Example:
package main
import (
         "fmt"
         "time"		 
)
func main() {
	t := time.Date(2015, 02, 21, 23, 10, 52, 211, time.UTC)	
	fmt.Println(t)
	fmt.Println("\n######################################\n")
	y := t.Year()
	mon := t.Month()
	d := t.Day()
	h := t.Hour()
	m := t.Minute()
	s := t.Second()
	n := t.Nanosecond()
	fmt.Println("Year   :",y)
	fmt.Println("Month  :",mon)
	fmt.Println("Day    :",d)
	fmt.Println("Hour   :",h)
	fmt.Println("Minute :",m)
	fmt.Println("Second :",s)
	fmt.Println("Nanosec:",n)
}
When you run the program, you get the following output:
C:\golang\time>go run t7.go 2015-02-21 23:10:52.000000211 +0000 UTC ###################################### Year : 2015 Month : February Day : 21 Hour : 23 Minute : 10 Second : 52 Nanosec: 211 C:\golang\time>

9) Convert specific UTC date time to PST, HST, MST and SGT.

Example:
package main
import (
    "fmt"
    "time"
)
func main() {
    t, err := time.Parse("2006 01 02 15 04", "2015 11 11 16 50")
	if err != nil {
        fmt.Println(err)
    }
    fmt.Println(t)
    loc, err := time.LoadLocation("America/Los_Angeles")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(loc)
    t = t.In(loc)
    fmt.Println(t.Format(time.RFC822))
	loc, err = time.LoadLocation("Singapore")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(loc)
    t = t.In(loc)
    fmt.Println(t.Format(time.RFC822))
	loc, err = time.LoadLocation("US/Hawaii")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(loc)
    t = t.In(loc)
    fmt.Println(t.Format(time.RFC822))
	loc, err = time.LoadLocation("EST")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(loc)
    t = t.In(loc)
    fmt.Println(t.Format(time.RFC822))
	loc, err = time.LoadLocation("MST")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(loc)
    t = t.In(loc)
    fmt.Println(t.Format(time.RFC822))
}
When you run the program, you get the following output:
C:\golang\time>go run t7.go 2015-11-11 16:50:00 +0000 UTC America/Los_Angeles 11 Nov 15 08:50 PST Singapore 12 Nov 15 00:50 SGT US/Hawaii 11 Nov 15 06:50 HST EST 11 Nov 15 11:50 EST MST 11 Nov 15 09:50 MST C:\golang\time>

10) Example to use Weekday and YearDay function.

Weekday returns the day of the week specified by t. YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, and [1,366] in leap years.

Example:
package main
import (
    "fmt"
    "time"
)
func main() {
    t,_ := time.Parse("2006 01 02 15 04", "2015 11 11 16 50")	
    fmt.Println(t.YearDay())	// 315
	fmt.Println(t.Weekday())	// Wednesday
	t,_ = time.Parse("2006 01 02 15 04", "2011 01 01 0 00")	
	fmt.Println(t.YearDay())
	fmt.Println(t.Weekday())
}
When you run the program, you get the following output:
C:\golang\time>go run t7.go 315 Wednesday 1 Saturday C:\golang\time>

11) Various examples of Carbon datetime package in Golang.

The package called Carbon can help make dealing with date/time in Golang much easier and more semantic so that our code can become more readable and maintainable.
Carbon is a package for Golang is available in Github. https://github.com/uniplaces/carbon

It provides some nice functionality to deal with dates in Golang. Specifically things like:
Easily calculate difference between dates
Dealing with timezones
Getting current time easily Converting a datetime into something readable
Parse an English phrase into datetime (first day of January 2016)
Add and Subtract dates (+ 2 weeks, -6 months)
Semantic way of dealing with dates

Install Carbon:
go get github.com/uniplaces/carbon

Add to your imports to start using Carbon
import "github.com/uniplaces/carbon"

Example:
package main
import (
    "fmt"    
	"github.com/uniplaces/carbon"
)
func main() {
    fmt.Printf("Right now is %s\n", carbon.Now().DateTimeString())
	today, _ := carbon.NowInLocation("Europe/London")
	fmt.Printf("Right now in London is %s\n", today)
	fmt.Printf("\n#######################################\n")	
	fmt.Printf("Tomorrow is %s\n", carbon.Now().AddDay())
	fmt.Printf("Yesterday is %s\n", carbon.Now().SubDay())
	fmt.Printf("After 5 Days %s\n", carbon.Now().AddDays(5))
	fmt.Printf("Before 5 Days %s\n", carbon.Now().SubDays(5))
	fmt.Printf("\n#######################################\n")
	fmt.Printf("Next Month is %s\n", carbon.Now().AddMonth())
	fmt.Printf("Last Month is %s\n", carbon.Now().SubMonth())
	fmt.Printf("\n#######################################\n")	
	fmt.Printf("Next week is %s\n", carbon.Now().AddWeek())
	fmt.Printf("Last week is %s\n", carbon.Now().SubWeek())
	fmt.Printf("\n#######################################\n")	
	fmt.Printf("Next Year %s\n", carbon.Now().AddYear())
	fmt.Printf("Last Year %s\n", carbon.Now().SubYear())
	fmt.Printf("After 5 Years %s\n", carbon.Now().AddYears(5))
	fmt.Printf("Before 5 Years %s\n", carbon.Now().SubYears(5))
	fmt.Printf("\n#######################################\n")	
	fmt.Printf("Next Hour %s\n", carbon.Now().AddHour())
	fmt.Printf("Last Hour %s\n", carbon.Now().SubHour())
	fmt.Printf("After 5 Mins %s\n", carbon.Now().AddMinutes(5))
	fmt.Printf("Before 5 Mins %s\n", carbon.Now().SubMinutes(5))
	fmt.Printf("\n#######################################\n")	
	fmt.Printf("Weekday? %t\n", carbon.Now().IsWeekday())
	fmt.Printf("Weekend? %t\n", carbon.Now().IsWeekend())
	fmt.Printf("LeapYear? %t\n", carbon.Now().IsLeapYear())
	fmt.Printf("Past? %t\n", carbon.Now().IsPast())
	fmt.Printf("Future? %t\n", carbon.Now().IsFuture())
	fmt.Printf("\n#######################################\n")
	fmt.Printf("Start of day:	%s\n", today.StartOfDay())
	fmt.Printf("End of day:	%s\n", today.EndOfDay())
	fmt.Printf("Start of month: %s\n", today.StartOfMonth())	
	fmt.Printf("End of month:	%s\n", today.EndOfMonth())
	fmt.Printf("Start of year:	%s\n", today.StartOfYear())
	fmt.Printf("End of year:	%s\n", today.EndOfYear())
	fmt.Printf("Start of week:	%s\n", today.StartOfWeek())
	fmt.Printf("End of week:	%s\n", today.EndOfWeek())
}
When you run the program, you get the following output:
C:\golang\time>go run t7.go Right now is 2017-08-27 22:38:07 Right now in London is 2017-08-27 18:08:07 ####################################### Tomorrow is 2017-08-28 22:38:07 Yesterday is 2017-08-26 22:38:07 After 5 Days 2017-09-01 22:38:07 Before 5 Days 2017-08-22 22:38:07 ####################################### Next Month is 2017-09-27 22:38:07 Last Month is 2017-07-27 22:38:07 ####################################### Next week is 2017-09-03 22:38:07 Last week is 2017-08-20 22:38:07 ####################################### Next Year 2018-08-27 22:38:07 Last Year 2016-08-27 22:38:07 After 5 Years 2022-08-27 22:38:07 Before 5 Years 2012-08-27 22:38:07 ####################################### Next Hour 2017-08-27 23:38:07 Last Hour 2017-08-27 21:38:07 After 5 Mins 2017-08-27 22:43:07 Before 5 Mins 2017-08-27 22:33:07 ####################################### Weekday? false Weekend? true LeapYear? false Past? false Future? false ####################################### Start of day: 2017-08-27 00:00:00 End of day: 2017-08-27 23:59:59 Start of month: 2017-08-01 00:00:00 End of month: 2017-08-31 23:59:59 Start of year: 2017-01-01 00:00:00 End of year: 2017-12-31 23:59:59 Start of week: 2017-08-21 00:00:00 End of week: 2017-09-03 23:59:59 C:\golang\time>