Go printing date to console

Day, Month and Year can be extracted from a time.Time type with the Date() method. It will return ints for both day and year, and a time.Month for the month. You can also extract the Hour, Minute and Second values with the Clock() method, which returns ints for all results.

For example:

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    y, mon, d := t.Date()
    h, m, s := t.Clock()
    fmt.Println("Year: ", y)
    fmt.Println("Month: ", mon)
    fmt.Println("Day: ", d)
    fmt.Println("Hour: ", h)
    fmt.Println("Minute: ", m)
    fmt.Println("Second: ", s)
}

Please remember that the Month variable (mon) is returned as a time.Month, and not as a string, or an int. You can still print it with fmt.Print() as it has a String() method.

Playground


You're actually pretty close :) Then return value from time.Now() is a Time type, and looking at the package docs here will show you some of the methods you can call (for a quicker overview, go here and look under type Time). To get each of the attributes you mention above, you can do this:

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    fmt.Println(t.Month())
    fmt.Println(t.Day())
    fmt.Println(t.Year())
}

If you are interested in printing the Month as an integer, you can use the Printf function:

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    fmt.Printf("%d\n", t.Month())
}

Tags:

Go