0
0
GoHow-ToBeginner · 3 min read

How to Get Current Time in Go: Simple Guide

In Go, you get the current time by calling time.Now() from the time package. This returns the current local time as a time.Time value.
📐

Syntax

The basic syntax to get the current time in Go is:

  • time.Now(): Returns the current local time as a time.Time object.

You must import the time package to use this function.

go
import "time"

func main() {
    currentTime := time.Now()
    // currentTime is a time.Time value representing now
}
💻

Example

This example shows how to print the current date and time in Go.

go
package main

import (
    "fmt"
    "time"
)

func main() {
    currentTime := time.Now()
    fmt.Println("Current time:", currentTime)
}
Output
Current time: 2024-06-15 14:30:45.123456789 +0000 UTC m=+0.000000001
⚠️

Common Pitfalls

Some common mistakes when getting current time in Go include:

  • Not importing the time package, causing a compile error.
  • Expecting time.Now() to return a string instead of a time.Time object.
  • Not formatting the time before printing, which can make output hard to read.

Always use time.Now() correctly and format the output if needed.

go
package main

import (
    "fmt"
    "time"
)

func main() {
    // Wrong: printing time.Time directly without formatting
    currentTime := time.Now()
    fmt.Println("Raw time:", currentTime)

    // Right: formatting time for readable output
    formatted := currentTime.Format("2006-01-02 15:04:05")
    fmt.Println("Formatted time:", formatted)
}
Output
Raw time: 2024-06-15 14:30:45.123456789 +0000 UTC m=+0.000000001 Formatted time: 2024-06-15 14:30:45
📊

Quick Reference

Summary tips for getting current time in Go:

  • Use time.Now() to get current local time.
  • The result is a time.Time object, not a string.
  • Format the time with Format() for readable output.
  • Remember to import time package.

Key Takeaways

Use time.Now() from the time package to get the current local time in Go.
The returned value is a time.Time object, which you can format for display.
Always import the time package before using time.Now().
Format time output with the Format method for better readability.
Avoid expecting time.Now() to return a string directly.