How to Print Specific date-time in Golang?
Go is a programming language that is well-suited for building high-performance, concurrent applications. One of the essential features of any application is the ability to work with date and time. In this article, we will explore how to print specific date-time in Go using the time package.
Using the Time Package in Go
The time package in Go provides a variety of functions for working with dates, times, and durations. The time.Time type represents a specific moment in time, and we can use its methods to format dates and times according to a specific layout.
To print a specific date-time in Go, we can create a time. Time value with the desired date and time and then use the time.Time.Format() method to convert the time value to a string in the desired format.
Example
Here is an example of how to print the current date and time in Go using the time package ?
package main
import (
"fmt"
"time"
)
func main() {
currentTime := time.Now()
fmt.Println("Current time:", currentTime)
}
Output
This code will print the current date and time in the default format of YYYY-MM-DD HH:MM:SS +0000 UTC.
Current time: 2023-04-20 11:16:42.524466246 +0000 UTC m=+0.000017874
Formatting Date and Time in Go
To format a date and time in a specific layout, we can use the time.Time.Format() method. This method takes a layout string as an argument that specifies how to format the date and time.
The layout string is a reference to a specific date and time by using a series of predefined layout values. Here are some of the most common layout values that you can use ?
Layout |
Description |
|---|---|
20023-05-02 |
Year, month, day |
15:04:05 |
Hour, minute, second |
Tue, 02 May 2023 15:04:05 MST |
Full date and time |
Example
Here is an example of how to format a date and time in Go using a custom layout string ?
package main
import (
"fmt"
"time"
)
func main() {
currentTime := time.Now()
formattedTime := currentTime.Format("Jan 02, 2006 3:04 PM")
fmt.Println("Formatted time:", formattedTime)
}
Output
This code will print the current date and time in the format of Jan 02, 2006 3:04 PM.
Formatted time: Apr 20, 2023 11:20 AM
Conclusion
In this article, we explored how to print specific date-time in Go using the time package. We learned how to format dates and times using the time.Time.Format() method and a layout string. By using the methods and layout values provided by the time package, you can easily format dates and times according to your specific needs in Go.
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP