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?
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 .
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.
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 .
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()) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With