Golang Date and Time (DateTime)

G
Time is incredibly important not only to us as humans but also to devices. When it comes to timestamps, they play an incredible role as they allow us to record and manipulate time-related data.

In Go, we have the “time” package which comes loaded with a lot of tools and features for working with time-related functions, including timestamps.

In this tutorial, we will learn about datetimes and how to work with them in Go without using external packages.

What is date time?

Date time refers to the combination of date (calendar date) and time (clock time) information. This includes details such as year, month, day, hour, minute, second and time zone offset.

Create a DateTime in Go

In Go, we can create a datetime using the time.Now() function that returns the current time in the local timezone.

An example is as follows:

package main
Import ,
“fmt”
“Time”
,
main work,, ,
present time :, Time,Now,,
FMT.println,“present time:”, present time,
,

This should return the current time and print it to the console. The function uses the time zone that is configured in the current device.

Example output:

present time: 2023,11,30 10,39,34.810855 ,0300 eat m,,0.000544667

Formatting date time

We can also format datetimes to follow specific layouts which are very useful in consistency and templates.

We can use layout constants like “2006-01-02 15:04:05” to define the desired format. Consider an example as follows:

package main
Import ,
“fmt”
“Time”
,
main work,, ,
present time :, Time,Now,,
FormattedTime:, present time.Format,“2006-01-02 15:04:05”,
FMT.println,“Formatted Time:”, formatted time,
,

Resulting output:

Formatted time: 2023,11,30 10,41,59

parsing date time

To convert a string to a datetime, we can use the “time.Parse” function, which specifies the layout to match the input string.

package main
Import ,
“fmt”
“Time”
,
main work,, ,
inputtime:, “2023-11-30 10:41:59”
parsedtime, Mistake:, Time,parse,“2006-01-02 15:04:05”, inputtime,
If to make a mistake , Zero ,
FMT.println,“Mistake:”, to make a mistake,
, Other ,
FMT.println,“Analysis Time:”, parsedtime,
,
,

The resulting output is as follows:

Parsed Time: 2023,11,30 10,41,59 ,0000 UTC

setting time zone

We can also specify the target time zone without actually modifying the time zone of the host machine.

We can use the “time.LoadLocation” function to get a “time.Location” value that represents a specific time zone and then set it to a datetime.

package main
Import ,
“fmt”
“Time”
,
main work,, ,
LOC, ,, Time,load location,“America/New York”,
present time :, Time,Now,,,In,LOC,
FMT.println,“Current time in New York:”, present time,
,

Output:

present time In New York: 2023,11,30 02,45,44.28346 ,0500 East

It returns the current time at the specified location.

conclusion

In this tutorial, we learned how to use and work with datetime in Go by leveraging the “time” package and the methods provided.

Add comment

By Ranjan