Nanoseconds to DateTime string

1,548 views
Skip to first unread message

Kamil Ciemniewski

unread,
Mar 26, 2011, 7:44:02 AM3/26/11
to golang-nuts
Hi,

I'd like to convert int64 which contains
date and time of last update of file in
nanoseconds - to date time string
that can be read by a human.

I've searched docs for time package but
havn't found anything useful.

How can I do it?

John Beisley

unread,
Mar 26, 2011, 8:14:13 AM3/26/11
to Kamil Ciemniewski, golang-nuts

I'd divide the int64 up into seconds and nanoseconds with % and /
operators, then use one of:

http://golang.org/pkg/time/#Time.SecondsToUTC
http://golang.org/pkg/time/#Time.SecondsToLocalTime

(Depending on the implied timezone of the original number)

And then get a formatted string with:

http://golang.org/pkg/time/#Time.Format

- John

John Beisley

unread,
Mar 26, 2011, 8:17:02 AM3/26/11
to golang-nuts
On Mar 26, 12:14 pm, John Beisley <great...@gmail.com> wrote:
> On 26 March 2011 11:44, Kamil Ciemniewski <ciemniewski.ka...@gmail.com> wrote:
>
> > Hi,
>
> > I'd like to convert int64 which contains
> > date and time of last update of file in
> > nanoseconds - to date time string
> > that can be read by a human.
>
> > I've searched docs for time package but
> > havn't found anything useful.
>
> > How can I do it?
>
> I'd divide the int64 up into seconds and nanoseconds with % and /
> operators, then use one of:
>
> http://golang.org/pkg/time/#Time.SecondsToUTChttp://golang.org/pkg/time/#Time.SecondsToLocalTime

Correction, using SecondsToUTC vs SecondsToLocalTime is for what
timezone you want to display, the input must be UTC.

chris dollin

unread,
Mar 26, 2011, 8:18:05 AM3/26/11
to Kamil Ciemniewski, golang-nuts

Something like:

t := time.SecondsToUTC( yourNanoSeconds / 1000000000 )
printMe := t.Format( yourLayoutString )

?

Chrus

--
Chris "allusive" Dollin

peterGo

unread,
Mar 26, 2011, 8:46:39 AM3/26/11
to golang-nuts
Kamil,

For example,

package main

import (
"fmt"
"time"
)

func main() {
ns := time.Nanoseconds()
t := time.SecondsToUTC(ns / 1e9)
dt := t.String()
fmt.Println(dt)
dt = t.Format(time.RFC3339)
fmt.Println(dt)
dt = t.Format("01/02/2006 15:04:05 -0700")
fmt.Println(dt)
}

Peter

On Mar 26, 7:44 am, Kamil Ciemniewski <ciemniewski.ka...@gmail.com>
wrote:

Kamil Ciemniewski

unread,
Mar 26, 2011, 12:00:59 PM3/26/11
to golang-nuts
John, Chris, Peter: thank you all:)
Your advice helped me alot.

Have a great day!
Reply all
Reply to author
Forward
0 new messages