How to Get the Current Time in Go

Use `time.Now()` from the standard `time` package to get the current local time, or `time.Now().UTC()` for Coordinated Universal Time.

Use time.Now() from the standard time package to get the current local time, or time.Now().UTC() for Coordinated Universal Time. These functions return a time.Time value that you can format, compare, or convert as needed.

Here is a practical example showing how to retrieve the current time and format it for display:

package main

import (
	"fmt"
	"time"
)

func main() {
	// Get current local time
	now := time.Now()
	fmt.Println("Local:", now)

	// Get current UTC time
	utc := time.Now().UTC()
	fmt.Println("UTC:", utc)

	// Format the time string (e.g., "2023-10-27 14:30:00")
	// Go uses a specific reference time: Mon Jan 2 15:04:05 MST 2006
	formatted := now.Format("2006-01-02 15:04:05")
	fmt.Println("Formatted:", formatted)
}

If you need to work with specific time zones, use time.LoadLocation to define the zone and then call In() on your time.Time object:

loc, err := time.LoadLocation("America/New_York")
if err != nil {
	panic(err)
}
nyTime := time.Now().In(loc)
fmt.Println("New York Time:", nyTime.Format("2006-01-02 15:04:05 MST"))

Remember that Go's formatting strings are not placeholders like %Y or %d; they must match the reference time Mon Jan 2 15:04:05 MST 2006 exactly to produce the desired output. For example, use 2006 for the four-digit year, 01 for the month, and 02 for the day. This approach ensures your timestamps are consistent across different systems and time zones.