Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date.now() equivalent in Go

In JavaScript, I can assign:

var now = Date.now();

Then use now to calculate as a number variable

time.Time type in Go doesn't seem to meet this demand. What is the Go equivalent of JavaScript's Date.now() ?

like image 943
necroface Avatar asked Mar 17 '16 03:03

necroface


2 Answers

Date.now() returns milliseconds since epoch UTC

The now() method returns the milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now as a Number.

To get that in Go, you can use:

time.Now().UTC().UnixNano() / 1e6
like image 135
sberry Avatar answered Oct 02 '22 16:10

sberry


You can use Now function from "time" package as follows:

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(time.Now())
    fmt.Println(time.Now().Date())
}

Sample output:

2009-11-10 23:00:00 +0000 UTC
2009 November 10

Here is function explanation from documentation:

func Now() Time

Now returns the current local time.

func (t Time) Date() (year int, month Month, day int)

Date returns the year, month, and day in which t occurs.

Watch it in Live Demo.

like image 34
Khamidulla Avatar answered Oct 02 '22 16:10

Khamidulla