Go by Example: Time

Go has built-in support for working with dates and times through the time package.

Here’s a basic example that demonstrates how to use the time package to get the current time, format it, and use it to measure elapsed time:

package main

import (

func main() {
	// Get the current time
	t := time.Now()
	fmt.Println("Current time:", t)

	// Format the time as a string
	fmt.Println("Formatted time:", t.Format("2006-01-02 15:04:05"))

	// Measure elapsed time
	start := time.Now()
	// Do some work here
	elapsed := time.Since(start)
	fmt.Println("Elapsed time:", elapsed)

In this example, the time.Now function is used to get the current time, which is stored in the t variable. The t.Format method is then used to format t as a string, using a format string that follows the reference time Mon Jan 2 15:04:05 2006.

Finally, the time.Since function is used to measure the elapsed time between the start time, which is set at the start of the program, and the current time.

The output of this program will be something like:

Current time: 2022-11-22 10:13:14.875424 +0100 CET
Formatted time: 2022-11-22 10:13:14
Elapsed time: 4.258µs

The time package provides a wide range of functionality for working with dates and times, including parsing and formatting times from and to strings, measuring and comparing durations, and working with time zones, calendars, and clocks.


Leave a Reply

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