Date and Time manipulation in Golang with examples

This golang tutorial explains how to work with golang time package.

In Go, the current time can be determined using time.Now(), provided by the time package.

The golang provides time package to measuring and displaying time. You can get current time based on selected timezone, add duration with current timezone etc using go time package.


. . .

Basic example

Go doesn’t use yyyy-mm-dd layout to format a time. Instead, you format a special layout parameter
Mon Jan 2 15:04:05 MST 2006

the same way as the time or date should be formatted. (This date is easier to remember when written as 01/02 03:04:05PM ‘06 -0700.)
package main

import (
"fmt"
"time"
)

const (
layoutISO = "2006-01-02"
layoutUS = "January 2, 2006"
)

func main() {
date := "1999-12-31"
t, _ := time.Parse(layoutISO, date)
fmt.Println(t) // 1999-12-31 00:00:00 +0000 UTC
fmt.Println(t.Format(layoutUS)) // December 31, 1999
}


The following predefined date and timestamp format constants are also available. The function

They have the following signatures:
func Parse(layout, value string) (Time, error) func (t Time) Format(layout string) string
. . .

Date Time in Golang

The date function return the time corresponding
yyyy-mm-dd hh:mm:ss + nsec nanoseconds.
package main

import (
"fmt"
"time"
)

const (
layoutISO = "2006-01-02"
layoutUS = "January 2, 2006"
)

func main() {
date := time.Date(2018, 01, 12, 22, 51, 48, 324359102, time.UTC)
fmt.Printf("date is :%s \n", date)
date = time.Date(2018, 01, 12, 22, 51, 48, 324359102, time.UTC)
fmt.Printf("date is :%s \n", date)
date = time.Now().UTC()
fmt.Printf("current date is :%s", date) // run on local env
}


The golang Date() output is:
date is :2018-01-12 22:51:48.324359102 +0000 UTC date is :2018-01-12 22:51:48.324359102 +0000 UTC current date is :2009-11-10 23:00:00 +0000 UTC
. . .

Add Years, Months and Days into Time

The AddDate method help to add Years, Months and Days to corresponding to the date, that could be any date.

You can pass integer type value of Years, Months and Days. The return type is time. You can pass any of the three parameters.

package main

import (
"fmt"
"time"
)

const (
layoutISO = "2006-01-02"
layoutUS = "January 2, 2006"
)

func main() {
date := time.Date(2018, 01, 12, 22, 51, 48, 324359102, time.UTC)
next_date := date.AddDate(1, 2, 1)

fmt.Printf("date is :%s\n", date)
fmt.Printf("date after adding (1,2,1) is :%s \n", next_date)

// use date.Add to add or substract time with (+ -) symbol
next_date1 := date.Add(+time.Hour * 24)
fmt.Printf("date after adding 24 hour is :%s \n", next_date1)

next_date2 := date.Add(-time.Hour * 24)
fmt.Printf("date after substracting 24 hour is :%s \n", next_date2)
}
date is :2018-01-12 22:51:48.324359102 +0000 UTC date after adding (1,2,1) is :2019-03-13 22:51:48.324359102 +0000 UTC date after adding 24 hour is :2018-01-13 22:51:48.324359102 +0000 UTC date after substracting 24 hour is :2018-01-11 22:51:48.324359102 +0000 UTC

. . .

Get Current UNIX Timestamp in Golang

You can get current time using now() method, Its have Unix() method that help to convert time into UNIX timestamp in golang.
package main

import (
"fmt"
"time"
)

func main() {
cur_time := time.Now().Unix()
fmt.Printf("current unix timestamp is :%v\n", cur_time)
}
current unix timestamp is :1257894000

More conversion options can be found at the time package
. . .

Parse Date String in Golang

You can parse date string in golang using parse method.
package main

import (
"fmt"
"time"
)

func main() {
date := "2018-10-24T18:50:23.541Z"
parse_time, _ := time.Parse(time.RFC3339, date)

fmt.Printf("current unix timestamp is :%s\n", date)
fmt.Printf("parse_time is :%s", parse_time)
}
current unix timestamp is :2018-10-24T18:50:23.541Z
parse_time is :2018-10-24 18:50:23.541 +0000 UTC

Use a format constants

Go provides in the time package some handy constants for commonly used formats:
const ( ANSIC = "Mon Jan _2 15:04:05 2006" UnixDate = "Mon Jan _2 15:04:05 MST 2006" RubyDate = "Mon Jan 02 15:04:05 -0700 2006" RFC822 = "02 Jan 06 15:04 MST" RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone RFC850 = "Monday, 02-Jan-06 15:04:05 MST" RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST" RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone RFC3339 = "2006-01-02T15:04:05Z07:00" RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00" Kitchen = "3:04PM" // Handy time stamps. Stamp = "Jan _2 15:04:05" StampMilli = "Jan _2 15:04:05.000" StampMicro = "Jan _2 15:04:05.000000" StampNano = "Jan _2 15:04:05.000000000" )

You can use them like this:
package main

import (
"fmt"
"time"
)

func main() {
t := time.Now()
fmt.Println(t.Format(time.ANSIC))
}
. . .


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

LoadLocation returns the Location with the given name.
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 }
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
. . .

How to Get Weekday and YearDay

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.
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()) }
315
Wednesday
1
Saturday
. . .

Get current Date and Time in EST, UTC and MST?

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 }
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
. . .


Get current date and time in various format in golang

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"))
}

Output:
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
. . .

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.
package main

import (
"fmt"
"time"
)

func main() {
currentTime := time.Now()
fmt.Println("######################################")
fmt.Println(currentTime.Format("2006-01-02 15:04:05"))

fmt.Println("######################################")
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("######################################")
year, month, day := time.Now().Date()
fmt.Println("Year   :", year)
fmt.Println("Month  :", month)
fmt.Println("Day    :", day)

fmt.Println("######################################")
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)
}
######################################

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
. . .


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

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))
}
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

Never miss a post from Ritesh swamy, when you sign up for Ednsquare.