45

I want to covert Unix time (1494505756) to UTC format just

import "time"
timeNow := time.Now()

I want to restore timeNow to UTC format. How to do that?

spoonsearch
  • 123
  • 3
  • 9
M.Mike
  • 663
  • 1
  • 6
  • 12

1 Answers1

106

You can get UTC and unix from time interface itself.

To convert unix timestamp to time object. Use this:

t := time.Unix(1494505756, 0)
fmt.Println(t)

func Unix(sec int64, nsec int64) Time

Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC. It is valid to pass nsec outside the range [0, 999999999]. Not all sec values have a corresponding time value. One such value is 1<<63-1 (the largest int64 value).

For UTC:

time.Now().UTC()

UTC returns t with the location set to UTC. Link: https://golang.org/pkg/time/#UTC

For Unix:

time.Now().Unix()

Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC. Link: https://golang.org/pkg/time/#Unix

Community
  • 1
  • 1
Abhilekh Singh
  • 2,845
  • 2
  • 18
  • 24
  • When creating a time from an epoch, is it common to want the timezone converted? I would have thought it more common to want it left in UTC. – Stephen Jul 01 '22 at 00:24