How to Use time.Time.Date() Function in Golang

Golang Time.Date() function is “used to check the year, month, and day in which the stated ‘t’ presents itself.”

Syntax

func (t Time) Date() (year int, month Month, day int)

Parameters

t: It is the stated time.

Return value

It returns the year, month, and day of the stated “t”.

Example 1: How to Use Time.Date() Function

package main

import (
  "fmt"
  "time"
)

func main() {
  // Define a specific date
  date := time.Date(2024, 5, 12, 0, 0, 0, 0, time.UTC)

  // Get the year, month, and day of the date
  year, month, day := date.Date()

  fmt.Println("Year of the date:", year)
  fmt.Println("Month of the date:", month)
  fmt.Println("Day of the date:", day)
}

Output

Year of the date: 2024
Month of the date: May
Day of the date: 12

Example 2: Get the current year, month, and day

package main

import (
  "fmt"
  "time"
)

func main() {
  // Get the current time
  now := time.Now()

  // Get the current year, month, and day
  year, month, day := now.Date()

  fmt.Println("Current Year:", year)
  fmt.Println("Current Month:", month)
  fmt.Println("Current Day:", day)
}

Output

Current Year: 2023
Current Month: July
Current Day: 1

That’s it.

Leave a Comment