How to parse a time without date in Go

Avatar of the author Willem Schots
26 Dec, 2023
~2 min.
RSS

In some applications it can be useful to accept only times as input, not times with dates.

For example, in scheduling or time-tracking scenarios there can be a need for “time of the day” over “full timestamp” inputs.

There are some things you need to consider when parsing times in Go:

  • What format are you expecting? 24-hour or 12-hour?
  • What precision do you need? Hours, minutes, seconds?
  • Be aware of default values for other time.Time elements.

24 Hour Format

In the 24-hour format the hours of the day are marked from midnight to midnight. The first hour begins at 00:00 and the days last hour at 23:00 (formatted as hours:minutes).

In Go you can use the reference layout "15:04" to parse times like this.

If you want to include seconds as well, you can use the existing constant time.TimeOnly:

// ...
TimeOnly = "15:04:05"
// ...

12 Hour (AM/PM) Format

In the 12-hour format the day is split into two 12-hour periods:

  • a.m. from Latin “ante meridiem”, meaning “before midday”.
  • p.m. from Latin “post meridium”, meaning “after midday”.

The first hour of the day starts at 12:00AM (“12 midnight”) and the last hour begins at 11:00PM.

When you only need minute-precision we can use the existing time.Kitchen constant:

// ...
Kitchen = "3:04PM"
// ...

If you need second-precision you can use the following reference layout: "3:04:05PM".

Other elements default to zero

Be aware that all elements of a time.Time that are not part of the time (years, days, location) will correspond to their default values.

  • Year and day will default to 1st of January 0000.
  • Location will default to the UTC Location.

If your app needs to handle these times in a different context, be sure to set the appropriate date and location.

main.go
package main

import (
	"fmt"
	"log"
	"time"
)

func parseAndPrint(layout, in string) {
	t, err := time.Parse(layout, in)
	if err != nil {
		log.Fatalf("failed to parse %s: %v", in, err)
	}
	fmt.Println(t)
}

func main() {
	// 24-hour: hours and minutes.
	parseAndPrint("15:04", "13:37")

	// 24-hour: hours, minutes and seconds.
	parseAndPrint(time.TimeOnly, "13:37:42")

	// 12-hour: hours and minutes.
	parseAndPrint(time.Kitchen, "1:37PM")

	// 12-hour: hours, minutes and seconds.
	parseAndPrint("3:04:05PM", "1:37:42PM")
}
🎓

Subscribe to my Newsletter and Keep Learning.

Gain access to more content and get notified of the latest articles:

I send emails every 1-2 weeks and will keep your data safe. You can unsubscribe at any time.

Hello! I'm the Willem behind willem.dev

I created this website to help new Go developers, I hope it brings you some value! :)

You can follow me on Twitter/X, LinkedIn or Mastodon.

Thanks for reading!