epoch Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/epoch/ Sat, 25 Jan 2020 17:42:21 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 epoch Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/epoch/ 32 32 159787465 Current Timestamp in Go (Golang) https://vikasboss.github.io/current-timestamp-in-golang/ https://vikasboss.github.io/current-timestamp-in-golang/#respond Fri, 24 Jan 2020 03:14:34 +0000 https://vikasboss.github.io/?p=1217 Overview In this tutorial, we will see how to get the current timestamp using the time package in Go. The current time can be represented in different ways time.Time object Unix Time...

The post Current Timestamp in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

In this tutorial, we will see how to get the current timestamp using the time package in Go. The current time can be represented in different ways

  • time.Time object
t := time.Now() //It will return time.Time object with current timestamp
  • Unix Time (Also known as Epoch Time) – It is the number of seconds elapsed since 00:00:00 UTC on 1 January 1970. This time is also known as the Unix epoch.
t := time.Now().Unix() 
//Will return number of seconds passed since Unix epoch
  • Unix Nano –  It is number of nanoseconds elapsed since 00:00:00 UTC on 1 January 1970
t := time.Now().UnixNano() 
//Will return number of nano seconds passed since Unix epoch
  • Unix MilliSecond – It is the number of milliseconds elapsed since 00:00:00 UTC on 1 January 1970
t:= int64(time.Nanosecond) * t.UnixNano() / int64(time.Millisecond)/ time.Millisecond  
//Number of millisecond elapsed since Unix epoch
  • Unix MicroSecond – It is the number of microseconds elapsed since 00:00:00 UTC on 1 January 1970
t:= int64(time.Nanosecond) * t.UnixNano() / int64(time.Millisecond)/ time.Millisecond  
//Number of millisecond elapsed since Unix epoch

Code

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now() //It will return time.Time object with current timestamp
    fmt.Printf("time.Time %s\n", t)

    tUnix := t.Unix()
    fmt.Printf("timeUnix: %d\n", tUnix)

    tUnixNano := t.UnixNano()
    fmt.Printf("timeUnixNano: %d\n", tUnixNano)

    tUnixMilli := int64(time.Nanosecond) * t.UnixNano() / int64(time.Millisecond)
    fmt.Printf("timeUnixMilli: %d\n", tUnixMilli)

    tUnixMicro := int64(time.Nanosecond) * t.UnixNano() / int64(time.Microsecond)
    fmt.Printf("timeUnixMicro: %d\n", tUnixMicro)
}

Output:

time.Time 2020-01-24 09:43:42.196901 UTC m=+0.000229700
timeUnix: 1579839222
timeUnixNano: 1579839222196901000
timeUnixMilli: 1579839222196
timeUnixMicro: 1579839222196901

The post Current Timestamp in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/current-timestamp-in-golang/feed/ 0 1217