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

Golang time.Time.Year() function is “used to find the year in which t occurs.” The function is defined under the “time” package.

Syntax

func (t Time) Year() int

Parameters

t: It is the stated time.

Return value

It returns the year in which the specified “t” occurs.

Example 1: How to Use time.Time.Tear() function

package main

import (
  "fmt"
  "time"
)

func main() {
  // Define a specific date
  date := time.Date(2040, 1, 1, 0, 0, 0, 0, time.UTC)

  // Get the year of the date
  year := date.Year()

  fmt.Println("Year of the date:", year)
}

Output

Year of the date: 2040

Example 2: Get the current year

To get the current Year in Golang, you can use the “time.Time.Year()” function.

package main

import (
  "fmt"
  "time"
)

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

  // Get the current year
  year := now.Year()

  fmt.Println("Current Year:", year)
}

Output

Current Year: 2023

Example 3: Declaring “t” in UTC

package main

import (
  "fmt"
  "time"
)

func main() {
  // Declaring t in UTC
  t := time.Date(2023, 11, 34,
  10, 85, 60, 0, time.UTC)

  yr := t.Year()

  fmt.Printf("The stated year in the"+
    " 't' specified is: %v\n", yr)
}

Output

The stated year in the 't' specified is: 2023

That’s it.

Leave a Comment