Go - Current Time Example

1. Introduction

Knowing how to work with time is essential in many applications, from logging and timestamping events to scheduling tasks. Go provides comprehensive support for time manipulation through the time package. This blog post shows how to get the current time and print it in various formats.


The current time in Go is represented by the Time struct in the time package. It provides numerous methods to format and manipulate time data.

2. Program Steps

1. Import the time package.

2. Get the current time using the time.Now() function.

3. Print the current time in different formats using the Format method.

4. Display the time in Unix format.

3. Code Program

package main

import (

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

	// Step 3: Print the current time in various formats
	fmt.Println("Default Format:", now)
	fmt.Println("RFC1123 Format:", now.Format(time.RFC1123))
	fmt.Println("Custom Format YYYY-MM-DD:", now.Format("2006-01-02"))

	// Step 4: Display the time in Unix format
	fmt.Println("Unix Time:", now.Unix())


Default Format: 2023-04-12 15:04:05.999999999 +0000 UTC
RFC1123 Format: Wed, 12 Apr 2023 15:04:05 UTC
Custom Format YYYY-MM-DD: 2023-04-12
Unix Time: 1649768645


1. package main - The package declaration for the Go program.

2. import "time" - Imports the time package, which contains functionality for working with dates and times.

3. time.Now() - Retrieves the current local time.

4. now.Format - Formats the current time using predefined layout constants (time.RFC1123) and custom patterns ("2006-01-02").

5. now.Unix() - Outputs the current time as a Unix timestamp, which is the number of seconds elapsed since January 1, 1970 UTC.

6. fmt.Println - Prints the time to the console in the specified formats.

7. The output displays the current time in the default format, a standard RFC1123 format, a custom YYYY-MM-DD format, and as a Unix timestamp.