去打印日期到控制台

I'm trying to pint the month, day, and year, separately to the console.

I need to be able to access each section of the date individually. I can get the whole thing using time.now() from the "time" package but I'm stuck after that.

Can anyone show me where I am going wrong please?

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
", t.Month())
}

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 can just parse the string to get year, month, & day.

package main

import (
    "fmt"
    "strings"
)

func main() {
    currTime := time.Now()
    date := strings.Split(currTime.String(), " ")[0]
    splits := strings.Split(date, "-")
    year := splits[0]
    month := splits[1]
    day := splits[2]

    fmt.Printf("%s-%s-%s
", year, month, day)
}