Skip to content

How to Set Hour and Minute for a Golang Time

Yes, sometimes we are surprised by Golang standard library! There is no method on time package that helps you to set (update) the hour, minute, second, and nanosecond of a time object (variable) 🙂

But we have this function to create any date that we want:

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

We can use the year, month, and day from the previous object and create a newly updated hour or minute time:

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    fmt.Println(t)
    modifiedTime := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
    fmt.Println(modifiedTime)
}
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *