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

Golang Time.Clock() function is “used to check the hour, minute, and second within the day in which the stated t presents itself.”

Syntax

func (t Time) Clock() (hour, min, sec int)

Parameters

t: It is the stated time.

Return value

The Clock() function returns the hour, minute, and second of the stated “t”.

Example 1: How to Use Time.Clock() Function in Go

package main

import (
  "fmt"
  "time"
)

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

  // Get the hour, minute, and second of the time
  hour, minute, second := timestamp.Clock()

  fmt.Println("Hour of the timestamp:", hour)
  fmt.Println("Minute of the timestamp:", minute)
  fmt.Println("Second of the timestamp:", second)
}

Output

Hour of the timestamp: 15
Minute of the timestamp: 30
Second of the timestamp: 45

Example 2: Get the current hour, minute, and second using Time.Clock()

package main

import (
  "fmt"
  "time"
)

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

  // Get the current hour, minute, and second
  hour, minute, second := now.Clock()

  fmt.Println("Current Hour:", hour)
  fmt.Println("Current Minute:", minute)
  fmt.Println("Current Second:", second)
}

Output

Current Hour: 22
Current Minute: 2
Current Second: 12

That’s it.

Leave a Comment