Ivan Coleto
Ivan Coleto

Reputation: 63

How to get time.Time from civil.Datetime

I have to use the civil.Datetime due to a Query response from a Bigquery database.

How can I get a time.Time date from civil.Datetime in Golang?

Something like:

var date time.Time = civil.ToTime(myCivilTime)

I checked the civil time docs : https://godoc.org/cloud.google.com/go/civil and there is a function that seems to make what I'm asking.

func (d Date) In(loc *time.Location) time.Time

But I am not sure about how should I set the *time.Location param.

Upvotes: 5

Views: 3959

Answers (2)

NicoGonzaMu
NicoGonzaMu

Reputation: 36

In addition to @peterSO's answer, if you just don't want to depend on the machine's region time, you can convert to string and then again to time.Time:

t, err := time.Parse("2006-01-02", myCivilDateTime.Date.String())

https://play.golang.org/p/MW9DrQ89Mwu

Upvotes: 0

peterSO
peterSO

Reputation: 166626

Use whatever time.Location makes sense for your application. For example,

package main

import (
    "fmt"
    "time"

    "cloud.google.com/go/civil"
)

func main() {
    now := time.Now().Round(0)
    fmt.Println(now, " : time Now")
    d := civil.DateTimeOf(now)
    fmt.Println(d, "           : civil DateTime")
    t := d.In(time.UTC)
    fmt.Println(t, " : time UTC")
    t = d.In(time.Local)
    fmt.Println(t, " : time Local")
    pacific, err := time.LoadLocation("America/Los_Angeles")
    if err != nil {
        fmt.Println(err)
        return
    }
    t = d.In(pacific)
    fmt.Println(t, " : time Pacific")
}

Output:

2018-07-03 12:46:15.728611385 -0400 EDT  : time Now
2018-07-03T12:46:15.728611385            : civil DateTime
2018-07-03 12:46:15.728611385 +0000 UTC  : time UTC
2018-07-03 12:46:15.728611385 -0400 EDT  : time Local
2018-07-03 12:46:15.728611385 -0700 PDT  : time Pacific

Upvotes: 7

Related Questions