How to get current time in milliseconds in GO? [SOLVED]


GO, GOLANG Solutions

Author: Tuan Nguyen
Reviewer: Deepak Prasad

Introduction

In this tutorial, we will try to get Unix time in milliseconds from a time.Time in Golang. The built-in time package provides some functions to help us to convert a time object to a Unix timestamp of type int64:

  • func (t Time) Unix() int64: Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC. The result does not depend on the location associated with t. Unix-like operating systems often record time as a 32-bit count of seconds, but since the method here returns a 64-bit value it is valid for billions of years into the past or future.
  • func (t Time) UnixMicro() int64: UnixMicro returns t as a Unix time, the number of microseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in microseconds cannot be represented by an int64 (a date before year -290307 or after year 294246). The result does not depend on the location associated with t.
  • func (t Time) UnixMilli() int64: UnixMilli returns t as a Unix time, the number of milliseconds elapsed since January 1, 1970 UTC.
  • func (t Time) UnixNano() int64: UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC

 

Example 1: Convert a time object to the Unix time in milliseconds using the UnixMulli() function

To convert a time to a UNIX time in milliseconds, we can easily use the UnixMilli() function. Let's take a look at the example below to see how to use this function:

package main

import (
	"fmt"
	"time"
)

func main() {
	// create a time variable
	now := time.Now()

	// convert to unix time in milliseconds
	unixMilli := now.UnixMilli()

	// print out the output
	fmt.Println("time:", now)
	fmt.Println("Unix time in milliseconds:", unixMilli)

        // a date value
        date := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
        mill := date.UnixMilli()
        fmt.Println(mill)
}

Output:

time: 2023-01-03 23:59:45.5443388 +0700 +07 m=+0.001585601
Unix time in milliseconds: 1672765185544
1672531200000

 

Example 2: Convert a time object to the Unix time in milliseconds using the Sub() function

The idea is to use the time.Sub() function to return the duration between the time variable with the zero value of time. The next step is to convert from a duration to milliseconds by using the Milliseconds() function:

func (d Duration) Milliseconds() int64: Milliseconds returns the duration as an integer millisecond count.

Here is an example of using the Sub() and Milliseconds() function to convert a time object to milliseconds in Golang:

package main

import (
	"fmt"
	"time"
)

func main() {
	// create a time variable
	now := time.Now()

	// calculate the different duration
	dur := now.Sub(time.Unix(0, 0))

	// convert duration to milliseconds:
	mill1 := dur.Milliseconds()

	fmt.Println("time:", now)
	fmt.Println("Unix time in milliseconds:", mill1)

	// a date value
	date := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)

	fmt.Println(date.Sub(time.Unix(0, 0)).Milliseconds())
}

Output:

time: 2023-01-04 00:16:00.1280876 +0700 +07 m=+0.001587501
Unix time in milliseconds: 1672766160128
1672531200000

 

Example 3: Convert from time.Now().UnixNano() to milliseconds

If you want to convert from time.Now().UnixNano() to milliseconds, just simply use a division. Let's take a look at the example below to see how we can convert from time.Now().UnixNano() to milliseconds using the division:

package main

import (
	"fmt"
	"time"
)

func main() {
	mill1 := unixnanoToMilli()

	fmt.Println("Unix time in milliseconds:", mill1)

	// a date value
	date := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)

	fmt.Println(date.UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond)))
}

func unixnanoToMilli() int64 {
	return time.Now().UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

Output:

Unix time in milliseconds: 1672766720766
1672531200000

The same division is illustrated in the example below:

package main

import (
	"fmt"
	"time"
)

func main() {
	mill1 := unixnanoToMilli()

	fmt.Println("Unix time in milliseconds:", mill1)

	// a date value
	date := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)

	fmt.Println(date.UnixNano() / 1e6)
}

func unixnanoToMilli() int64 {
	return time.Now().UnixNano() / 1e6
}

NOTE:

The UnixNano result is undefined if the Unix time in nanoseconds cannot be represented by an int64 (a date before the year 1678 or after 2262), so be careful when you try to convert the edge cases.

 

Summary

In this tutorial, I have provided with you some examples of converting a time.Time to milliseconds or time.Now().UnixNano() to milliseconds. From Go 1.19, we can simply use the UnixMulli() function for UNIX time milliseconds conversion. Another way to convert from a time.Time to milliseconds is to convert it to a duration and then convert the duration to milliseconds by using the Sub() function. If you want to get the milliseconds from the time.Now().UnixNano(), you can make a division but be careful with the boundary because the UnixNano result is undefined if the Unix time in nanoseconds cannot be represented by an int64

 

References

https://pkg.go.dev/time

 

Tuan Nguyen

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment