How to Get Current Date and Time in Various Format in Golang?


Getting the current date and time is a common task in many programming applications, from logging events to scheduling tasks. In this article, we will explore how to get the current date and time in various formats in Golang.

Using The Time Package

The time package in Golang provides a simple way to work with dates and times. We can use the time.Now() function to get the current date and time in the local timezone.

Example

Here's an example −

package main

import (
   "fmt"
   "time"
)

func main() {
   now := time.Now()
   fmt.Println("Current date and time:", now)
}

In this code, we use the time.Now() function to get the current date and time, and then we print it to the console.

Output

Current date and time: 2023-05-04 16:59:03.598695926 +0000 UTC m=+0.000014238

Formatting Date and Time

The time package also provides a Format() function that allows us to format the date and time in various ways. We can use a layout string to specify the format we want. Here are some common format options −

  • 2023-04-14 − Year, month, and day in the format "YYYY-MM-DD"

  • 15:04:05 − Hour, minute, and second in the format "HH:MM:SS"

  • Fri Apr 14 15:04:05 MST 2023 − Full date and time in the format "Fri Apr 14 15:04:05 MST 2023"

Example

Here's an example of using the Format() function to format the current date and time −

package main

import (
   "fmt"
   "time"
)
func main() {
   now := time.Now()
   fmt.Println("Current date and time (RFC3339):", now.Format(time.RFC3339))
   fmt.Println("Current date (YYYY-MM-DD):", now.Format("2006-01-02"))
   fmt.Println("Current time (HH:MM:SS):", now.Format("15:04:05"))
   fmt.Println("Current date and time (Mon Jan 2 15:04:05 MST 2006):", now.Format("Mon Jan 2 15:04:05 MST 2006"))
}

In this code, we use the Format() function to format the current date and time in various ways. We use the time.RFC3339 constant to format the date and time in the RFC3339 format.

Output

Current date and time (RFC3339): 2023-05-04T17:02:52Z
Current date (YYYY-MM-DD): 2023-05-04
Current time (HH:MM:SS): 17:02:52
Current date and time (Mon Jan 2 15:04:05 MST 2006): Thu May 4 17:02:52 UTC 2023

Conclusion

Getting the current date and time in various formats in Golang is simple and straightforward using the time package. We can use the time.Now() function to get the current date and time in the local timezone, and the Format() function to format the date and time in various ways using a layout string.

Updated on: 05-May-2023

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements