Unix Timestamp & Date Time Guide

Code Examples In Go


Introduction

The time package in Go provides powerful tools for working with dates, times, and time zones.
It supports formatting and parsing using a unique reference layout, date and time arithmetic, time zone conversions, and Unix timestamps.
This guide explores the key features and best practices for managing date and time effectively in Go, ensuring robust and timezone-aware applications.


Get Current Time

The function time.Now() is commonly used to retrieve the current local time as a time.Time object.
This object includes details such as the year, month, day, hour, minute, second, and nanosecond.

Method:

1time.Now()

Example:

1package main
2
3import (
4	"fmt"
5	"time"
6)
7
8func main() {
9	t := time.Now()
10	fmt.Println(t)
11}

Result:

12024-11-10 23:00:00 +0000 UTC m=+0.000000001

Get Unix timestamp

Unix timestamp represents the number of seconds or milliseconds that have elapsed since January 1, 1970 00:00:00 UTC (the Unix epoch).
Unix timestamps are commonly used for time-related calculations, data storage, or interoperability with other systems.
The time package in Go provides the Unix() and UnixMilli()methods on time.Time objects to retrieve the Unix timestamp in seconds or milliseconds, respectively.

Method:

1time.Unix()      // unix timestamp in seconds
2time.UnixMilli() // unix timestamp in milliseconds
3time.UnixMicro() // unix timestamp in microseconds
4time.UnixNano()  // unix timestamp in nanoseconds

Example:

1package main
2
3import (
4	"fmt"
5	"time"
6)
7
8func main() {
9	t := time.Now()
10	fmt.Printf("current unix time in seconds %v\n", t.Unix())
11	fmt.Printf("current unix time in milliseconds %v\n", t.UnixMilli())
12	fmt.Printf("current unix time in microseconds %v\n", t.UnixMicro())
13	fmt.Printf("current unix time in nanoseconds %v\n", t.UnixNano())
14}

Result:

1current unix time in seconds 1732718795
2current unix time in milliseconds 1732718795495
3current unix time in microseconds 1732718795495663
4current unix time in nanoseconds 1732718795495663500

Construct New Time

In Go, you can construct a new time.Time object using the time.Date() function.
This function provides a way to create specific points in time by specifying the year, month, day, hour, minute, second, nanosecond, and timezone.
This is particularly useful for initializing times for scheduling, testing, or any scenario requiring precise control over time values.
Other functions in time package are also helpful.

Method:

1// parses a formatted string
2time.Parse(layout, value string)
3// parses a formatted string with timezone
4time.ParseInLocation(layout, value string, loc *Location)
5
6// returns the local Time corresponding to the given Unix time
7// sec seconds and nsec nanoseconds since January 1, 1970 UTC
8time.Unix(sec int64, nsec int64)
9// usec microseconds since January 1, 1970 UTC
10time.UnixMicro(usec int64)
11// msec milliseconds since January 1, 1970 UTC
12time.UnixMilli(msec int64)
13
14// creates a time from a date and a time
15time.Date(year, month, day, hour, minute, second, nanosecond int, loc *Location)

Example:

1package main
2
3import (
4	"fmt"
5	"time"
6)
7
8func main() {
9	// Define the time layout and input string
10	layout := "2006-01-02 15:04:05"
11	input := "2024-11-29 15:30:00"
12
13	// Parse the input string into a time.Time object
14	parsedTime, err := time.Parse(layout, input)
15	if err != nil {
16		fmt.Println("Error parsing time:", err)
17		return
18	}
19	fmt.Println("Parsed time:", parsedTime)
20
21	// Load a specific time zone location
22	location, err := time.LoadLocation("America/New_York")
23	if err != nil {
24		fmt.Println("Error loading location:", err)
25		return
26	}
27
28	// Parse the input string into a time.Time object using the specified location
29	parsedLocationTime, err := time.ParseInLocation(layout, input, location)
30	if err != nil {
31		fmt.Println("Error parsing time:", err)
32		return
33	}
34
35	// Output the parsed time
36	fmt.Println("Parsed time with location:", parsedLocationTime)
37
38	// create time from Unix timestamp
39	unixTimestamp := int64(1672531200) // Replace with your Unix timestamp
40	// Convert Unix timestamp to time.Time
41	timeFromUnix := time.Unix(unixTimestamp, 0)
42	// Output the created time
43	fmt.Println("Time from Unix timestamp:", timeFromUnix)
44
45	// create time using time.Date
46	createdTime := time.Date(2024, time.November, 29, 15, 31, 24, 0, time.UTC)
47
48	// Output the created time
49	fmt.Println("Created time:", createdTime)
50}

Result:

1Parsed time: 2024-11-29 15:30:00 +0000 UTC
2Parsed time with location: 2024-11-29 15:30:00 -0500 EST
3Time from Unix timestamp: 2023-01-01 08:00:00 +0800 +08
4Created time: 2024-11-29 15:31:24 +0000 UTC

Convert Unix timestamp to readable Date Time

Unix timestamps, also known as Epoch time, represent the number of seconds that have elapsed since January 1, 1970 (UTC).
While Unix timestamps are commonly used in programming for their simplicity and efficiency, they are not human-readable. Converting these timestamps into a readable date-time format is a crucial step in many applications, such as logging, data analysis, and user-facing interfaces.
In Go, with its powerful time package, makes it straightforward to handle time-related operations, including the conversion of Unix timestamps into formatted date-time strings.

Method:

1// returns a textual representation of the time
2time.Format(layout string)
3
4// Date returns the year, month, and day in which t occurs.
5time.Date()
6
7// Clock returns the hour, minute, and second
8time.Clock()

Example:

1package main
2
3import (
4	"fmt"
5	"time"
6)
7
8func main() {
9	unixTimestamp := int64(1672531200) // Replace with your Unix timestamp
10
11	// Convert Unix timestamp to time.Time
12	t := time.Unix(unixTimestamp, 0)
13
14	// Format and print the date and time
15	fmt.Println("Readable Date and Time:", t.Format("2006-01-02T15:04:05"))
16
17	// Get year, month, and day
18	year, month, day := t.Date()
19	fmt.Println("Year:", year, "Month:", month, "Day:", day)
20}

Result:

1Readable Date and Time: 2023-01-01T08:00:00
2Year: 2023 Month: January Day: 1
3Hour: 8 Minute: 0 Second: 0

Convert Date Time to Unix timestamp

When working with date-time values in human-readable formats, converting them into Unix timestamps is often necessary for tasks such as scheduling, logging, or interacting with APIs that use Unix time.
Go provides a robust time package that simplifies handling and manipulating time data.

Method:

1// parses a formatted string
2time.Parse(layout, value string)
3
4// creates a time from a date and a time
5time.Date(year, month, day, hour, minute, second, nanosecond int, loc *Location)

Example:

1package main
2
3import (
4	"fmt"
5	"time"
6)
7
8func main() {
9	// Define the time layout and input string
10	layout := "2006-01-02 15:04:05"
11	input := "2024-11-29 15:30:00"
12
13	// Parse the input string into a time.Time object
14	parsedTime, err := time.Parse(layout, input)
15	if err != nil {
16		fmt.Println("Error parsing time:", err)
17		return
18	}
19	fmt.Println("Unix timestamp after parsing:", parsedTime.Unix())
20
21	// create time using time.Date
22	createdTime := time.Date(2024, time.November, 29, 15, 31, 24, 0, time.UTC)
23
24	// Output the created time
25	fmt.Println("Unix timestamp after time.Date:", createdTime.Unix())
26}

Result:

1Unix timestamp after parsing: 1732894200
2Unix timestamp after time.Date: 1732894284

Change Time Zone

Working with different time zones is a common challenge in software development, especially when building applications that cater to a global audience.
Proper time zone handling ensures that events, logs, and schedules are accurately represented and understood, regardless of the location of user.
Go offers a comprehensive time package that simplifies working with time zones.

Method:

1// FixedZone returns a Location that always uses the 
2// given zone name and offset (seconds east of UTC).
3time.FixedZone(name string, offset int)
4
5// LoadLocation returns the Location with the given name.
6time.LoadLocation(name string)

Example:

1package main
2
3import (
4	"fmt"
5	"time"
6)
7
8func main() {
9	// using fixed zone
10	loc := time.FixedZone("UTC-8", -8*60*60)
11	t := time.Date(2023, time.November, 10, 23, 0, 0, 0, loc)
12	fmt.Println("The time with FixedZone:", t.Format("2006-01-02 15:04:05 -0700"))
13
14	// using LoadLocation
15	loadedLoc, err := time.LoadLocation("America/New_York")
16	if err != nil {
17		fmt.Println("Error loading location:", err)
18		return
19	}
20
21	timeInUTC := time.Date(2023, 8, 30, 12, 0, 0, 0, time.UTC)
22	fmt.Println("Time in loaded location:", timeInUTC.In(loadedLoc))
23}

Result:

1The time with FixedZone: 2023-11-10 23:00:00 -0800
2Time in loaded location: 2023-08-30 08:00:00 -0400 EDT

Time Addition and Subtraction

Manipulating date-time values is a fundamental task in software development, whether scheduling events, calculating durations, or determining past or future dates.
Adding or subtracting time intervals like days, hours, or minutes is a common requirement in many applications, and doing so accurately is essential.
Go provides robust support for date-time operations through its time package. This package includes methods to perform precise additions and subtractions on date-time values, making it easy to handle complex time calculations.

Method:

1// Add returns the time t+d.
2time.Add(d Duration)
3// Adding the given number of years, months, and days
4time.AddDate(years int, months int, days int)
5
6// Sub returns the duration t-u
7time.Sub(u Time)
8
9// Since returns the time elapsed since t. 
10// It is shorthand for time.Now().Sub(t).
11time.Since(t Time)

Example:

1package main
2
3import (
4	"fmt"
5	"time"
6)
7
8func main() {
9	currentTime := time.Date(2023, 12, 1, 10, 0, 0, 0, time.UTC)
10	fmt.Println("Current Time:", currentTime)
11
12	// Time addition
13	timeAfter := currentTime.Add(time.Hour * 2)
14	fmt.Println("Time After 2 Hours:", timeAfter)
15
16	nextDay := currentTime.AddDate(0, 0, 1)
17	fmt.Println("Next Day:", nextDay)
18
19	// Use the negetive sign to get the earlier time
20	timeBefore := currentTime.Add(-time.Hour * 2)
21	fmt.Println("Time Before 2 Hours:", timeBefore)
22
23	yesterday := currentTime.AddDate(0, 0, -1)
24	fmt.Println("Yesterday:", yesterday)
25
26	// Time difference using time.Sub
27	time1 := time.Date(2024, 12, 1, 10, 0, 0, 0, time.UTC)
28	time2 := time.Date(2024, 12, 1, 8, 30, 0, 0, time.UTC)
29
30	duration := time1.Sub(time2)
31	fmt.Println("Duration Difference:", duration)
32
33	// Time difference
34	start := time.Now() // Record the start time
35
36	// Simulate some work with sleep
37	time.Sleep(2 * time.Second)
38
39	// calculate the elapsed time using time.Since
40	elapsed := time.Since(start) // Calculate the elapsed time
41	fmt.Println("Elapsed time using Since:", elapsed)
42}

Result:

1Current Time: 2023-12-01 10:00:00 +0000 UTC
2Time After 2 Hours: 2023-12-01 12:00:00 +0000 UTC
3Next Day: 2023-12-02 10:00:00 +0000 UTC
4Time Before 2 Hours: 2023-12-01 08:00:00 +0000 UTC
5Yesterday: 2023-11-30 10:00:00 +0000 UTC
6Duration Difference: 1h30m0s
7Elapsed time using time.Since: 2.0085591s

Pause or sleep for a specific time

In programming, there are situations where you need to pause the execution of your code for a specific duration. This could be for implementing delays, rate-limiting API calls, waiting for asynchronous processes, or simulating real-world timing in your application.
Go provides a simple and efficient way to achieve this using the time package, which includes the Sleep function. With time.Sleep(), you can easily pause program execution for a precise duration, whether in milliseconds, seconds, or longer intervals.

Method:

1time.Sleep(d Duration)

Example:

1package main
2
3import (
4	"fmt"
5	"time"
6)
7
8func main() {
9	fmt.Println("Start")
10
11	// Sleep for 1 second
12	time.Sleep(1 * time.Second)
13
14	fmt.Println("End")
15}

Result:

1Start
2End