Fragment Description:



Epoch.
.
A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the [Unix epoch](http://en.wikipedia.org/wiki/Unix_time).
Here's how to do it in Go.


timeEpoch

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:35

/* ... <== see fragment description ... */

package main

import "fmt"
import "time"

func main() {
    var p = fmt.Println
    // Use `time.Now` with "Unix" or "UnixNano" to get
    // elapsed time since the Unix epoch in seconds or
    // nanoseconds, respectively.
    now := time.Now()
    secs := now.Unix()
    nanos := now.UnixNano()
    fmt.Println(now)
    p("====================")
    // Note that there is no "UnixMillis", so to get the
    // milliseconds since epoch you'll need to manually
    // divide from nanoseconds.
    millis := nanos / 1000000
    fmt.Println(secs)
    fmt.Println(millis)
    fmt.Println(nanos)
    p("====================")
    // You can also convert integer seconds or nanoseconds
    // since the epoch into the corresponding "time".
    fmt.Println(time.Unix(secs, 0))
    fmt.Println(time.Unix(0, nanos))
    // Time in the past
    fmt.Println(time.Unix(1, 0))
    fmt.Println(time.Unix(0, 1))
}

/* Expected Output:
2015-09-15 19:25:25.4279491 +0100 BST
====================
1442341525
1442341525427
1442341525427949100
====================
2015-09-15 19:25:25 +0100 BST
2015-09-15 19:25:25.4279491 +0100 BST
1970-01-01 00:00:01 +0000 GMT
1970-01-01 00:00:00.000000001 +0000 GMT
*/



Comments