Golang Time

Built-in Array Func Map Slice Const Fmt For If Index Recover Sort Split Strings Switch Time


Time. Programs often handle times and dates.
They read strings in from files,
parse them,
test them for validity. Times are changed.

Calendar: June 15

With the time package, we access many usable funcs on the Time struct. These methods are reusable and tested. This is a clear advantage.

Go func

Now example. Let us start with this simple example. We import the "time" package in the import block at the top. We invoke the Now method from the time package. It returns a struct.

Year:With year we get an int equal to the year field in the Time struct. Here it returns 2015.

Month:This returns the month of the time struct as an int. When we use Println, its String method displays it in a readable way.

Day:This is the day field of the Time struct—not the total number of days in the time.

Based on:

Golang 1.4

Golang program that uses time, Year, Month, Day

package main

import (

func main() {
    // Get the current time.
    t := time.Now()

    // Print year, month and day of the current time.


2015-01-28 02:33:21.0351194 -0800 PST

Parse. With this func we convert a string to a Time struct. Parse receives two strings: a form string and the value we are parsing.

Return:Parse() returns two things: the Time struct and an error (if any). We can use the blank identifier to ignore the error.

Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be Mon Jan 2 15:04:05 -0700 MST 2006 would be interpreted if it were the value.

Time: golang.org
Golang program that uses time, Parse

package main

import (

func main() {
    // This is the value we are trying to parse.
    value := "January 28, 2015"

    // The form must be January 2,2006.
    form := "January 2, 2006"

    // Parse the string according to the form.
    t, _ := time.Parse(form, value)


2015-01-28 00:00:00 +0000 UTC

With the Time struct, we gain a way to represent a point in time (a Date). And with the methods in time, we can manipulate it. We cannot go back in time, but we can represent it.