Simple types — Date and time — getting of year, month, day

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.

Getting the Current Year, Month, and Day

Here’s an example demonstrating how to get the current year, month, and day using time.Now() and the Year, Month, and Day methods.

Example Code

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)
}

Explanation

  1. Get the Current Date and Time:
  2. Extract the Year:
  3. Extract the Month:
  4. Extract the Day:
  5. Print the Year, Month, and Day:

Detailed Output

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

Practical Example: Displaying the Current Date in Different Formats

You can also combine these methods to display the current date in different formats.

Example: Displaying 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)
}

Explanation