blackgreen
blackgreen

Reputation: 45041

How to add time zone information to existing time.Time

Let's say that I have the following:

As stated in Postgres documentation:

The CURRENT_TIMESTAMP() function returns a TIMESTAMP WITH TIME ZONE that represents the date and time at which the transaction started.

Therefore the following statement is silently converting a local timestamp into an absolute timestamp:

INSERT INTO foo (id, timestamp_column) VALUES (0, CURRENT_TIMESTAMP);

Let's say that a Go program reads this data into a time.Time object, that object will have an empty Location:

fmt.Println(timeFromDb.Location().String() == "") // true

which is interpreted as UTC. At this point I do know that the Go time timeFromDb is not actually UTC, and I also know what the database time zone setting is.

How can I set the correct time zone into this time object? In practice:

// before
fmt.Println(timeFromDb)            // 2009-11-10 10:00:00
fmt.Println(timeFromDb.Location()) // <empty>
fmt.Println(timeFromDb.UTC())      // 2009-11-10 10:00:00

// magic?

// after
fmt.Println(timeFromDb)            // 2009-11-10 10:00:00
fmt.Println(timeFromDb.Location()) // America/Vancouver
fmt.Println(timeFromDb.UTC())      // 2009-11-10 18:00:00

Upvotes: 2

Views: 86

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51632

You can reinterpret it:

loc,_:=time.LoadLocation("America/Vancouver")
t2:=timeFromDb.In(loc)
_,off:=t2.Zone()
theTime:=t2.Add(-time.Duration(off)*time.Second)

You can also do some string manipulation, but I suspect this is faster.

Upvotes: 2

Related Questions