Enter console print date

I am trying to print the month, day, and year separately for the console.

I need to have access to each section of the date separately. I can get all this using time.now() from the "time" package, but I got stuck after that.

Can someone show me where I'm going wrong please

+15
go
source share
3 answers

You are actually pretty close :) Then the return value from time.Now() is a type of Time and looking at the package documents here will show you some of the methods you can call (for a quicker review, go here and look under type Time ). To get each of the above attributes, 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 want to print 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()) } 
+17
source share

Day, month and year can be extracted from time.Time using Date() . It will return ints for day and year and time.Month for the month. You can also extract the Hour, Minute, and Second values ​​using the Clock() method, which returns an int 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) } 

Remember that the Month ( mon ) variable is returned as time.Month , and not as a string or int. You can print it using fmt.Print() since it has a String() method.

Playground

+1
source share

You can simply parse the string to get the year, month and 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\n", year, month, day) } 
0
source share

All Articles