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

Golang time.Time.Hour() function is “used to check the hour within the day in which the stated ‘t’ presents itself in the range [0, 23].”

Syntax

func (t Time) Hour() int

Parameters

t: It is the stated time.

Return value

The Hour() function returns the hour within the day the stated “t” occurs.

Example 1: How to Use time.Time.Hour() Function

package main

import (
  "fmt"
  "time"
)

func main() {
  // Define a specific date and time
  timestamp := time.Date(2023, 10, 10, 15, 30, 0, 0, time.UTC)

  // Get the hour of the time
  hour := timestamp.Hour()

  fmt.Println("Hour of the timestamp:", hour)
}

Output

Hour of the timestamp: 15

Example 2: How to Get Current Hour in Go

To get the current hour in Go, you can use the “time.Time.Hour()” function.

package main

import (
  "fmt"
  "time"
)

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

  // Get the current hour
  hour := now.Hour()

  fmt.Println("Current Hour:", hour)
}

Example 3: Declaring “t” in UTC

package main

import (
  "fmt"
  "time"
)

func main() {
  // Declaring t in UTC
  t := time.Date(2023, 4, 30,
  25, 40, 01, 0, time.UTC)

  // Calling Hour method
  hr := t.Hour()

  // Prints hour as specified
  fmt.Printf("The stated hour"+
    " within the day is: %v\n", hr)
}

Output

The stated hour within the day is: 1

That’s it.

Leave a Comment