Open In App

time.Time.Year() Function in Golang with Examples

In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Year() function in Go language is used to find the year in which the specified “t” happens. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.

Syntax:

func (t Time) Year() int

Here, “t” is the stated time.

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

Example 1:




// Golang program to illustrate the usage of
// Time.Year() function
  
// Including main package
package main
  
// Importing fmt and time
import "fmt"
import "time"
  
// Calling main
func main() {
  
    // Declaring t in UTC
    t := time.Date(2019, 6, 5, 11, 
             35, 04, 0, time.UTC)
  
    // Calling Year method
    yr := t.Year()
  
    // Prints year as specified
    fmt.Printf("The stated year in the"+
          " 't' specified is: %v\n", yr)
}

Output:

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

Example 2:




// Golang program to illustrate the usage of
// Time.Year() function
  
// Including main package
package main
  
// Importing fmt and time
import "fmt"
import "time"
  
// Calling main
func main() {
  
    // Declaring t in UTC
    t := time.Date(2019, 13, 35, 
       28, 89, 63, 0, time.UTC)
  
    // Calling Year method
    yr := t.Year()
  
    // Prints year as specified
    fmt.Printf("The stated year in the"+
         " 't' specified is: %v\n", yr)
}

Output:

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

Here, the “t” stated above has values that are out of usual range but they are normalized while conversion.


Article Tags :