In Go, you can get the current year, month, and day from a time.Time object using the Year, Month, and Day methods provided by the time package. These methods are straightforward and allow you to extract these components from a time.Time object easily.
Here’s an example demonstrating how to get the current year, month, and day using time.Now() and the Year, Month, and Day methods.
package main
import (
"fmt"
"time"
)
func main() {
// Get the current date and time
currentTime := time.Now()
// Extract the year, month, and day
year := currentTime.Year()
month := currentTime.Month()
day := currentTime.Day()
// Print the current year, month, and day
fmt.Printf("Current year: %d\\\\n", year)
fmt.Printf("Current month: %s\\\\n", month)
fmt.Printf("Current day: %d\\\\n", day)
}
time.Now() to get the current local date and time.currentTime.Year() to get the current year as an integer.currentTime.Month() to get the current month as a time.Month type.currentTime.Day() to get the current day as an integer.fmt.Printf.The output of the above code will look something like this (the exact output will vary based on the current date):
Current year: 2023
Current month: May
Current day: 26
You can also combine these methods to display the current date in different formats.
package main
import (
"fmt"
"time"
)
func main() {
// Get the current date and time
currentTime := time.Now()
// Extract the year, month, and day
year := currentTime.Year()
month := currentTime.Month()
day := currentTime.Day()
// Display the current date in different formats
fmt.Printf("Current date (YYYY-MM-DD): %d-%02d-%02d\\\\n", year, month, day)
fmt.Printf("Current date (DD/MM/YYYY): %02d/%02d/%d\\\\n", day, month, year)
fmt.Printf("Current date (Month Day, Year): %s %d, %d\\\\n", month, day, year)
}