Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go printing date to console

Tags:

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?

like image 522
tjames68w Avatar asked Sep 05 '13 03:09

tjames68w


People also ask

What is FMT Println in go?

The fmt. Println function in the GO programming language is a function used to print out a formatted string to the console. fmt. Println does not support custom format specifiers, which means only the default formats are used to format the string .

How do I print a structure in go?

Printf with #v includes main. Fields that is the structure's name. It includes “main” to distinguish the structure present in different packages. Second possible way is to use function Marshal of package encoding/json.

How do you print variables in go?

To print a variable's type, you can use the %T verb in the fmt. Printf() function format. It's the simplest and most recommended way of printing type of a variable. Alternatively, you can use the TypeOf() function from the reflection package reflect .


1 Answers

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()) } 
like image 151
RocketDonkey Avatar answered Sep 20 '22 19:09

RocketDonkey