Search code examples
gotimelocaltime

Convert time string


I have a datetime string coming from the SQL database. It is stored in local Amsterdam time. I want to convert it to RFC3339 format to add it in a XML output. My time string (timeStringFromDb) has the following value: "2020-11-27 09:04:05"

I use the following code to convert the datetime string.

timezone, _ := time.LoadLocation("Europe/Amsterdam")
t, _ := time.Parse("2006-01-02 15:04:05", timeStringFromDb)
t = t.In(timezone)
fmt.Println(t.Format(time.RFC3339))

The result is: 2020-11-27T10:04:05+01:00

I would have expected 2020-11-27T09:04:05+01:00

I looks like the t.In function also converts the time, but I just want to add the timezone as the time is already local. Any ideas?


Solution

  • One way would to append the timezone to the string coming from the database:

    timeStringFromDb := "2020-11-27 09:04:05"
    timezone, _ := time.LoadLocation("Europe/Amsterdam")
    t, _ := time.Parse("2006-01-02 15:04:05Z07:00", timeStringFromDb+"+01:00")
    t = t.In(timezone)
    fmt.Println(t.Format(time.RFC3339))
    

    But this in not very elegant, I would suggest to change the timezone of the database to UTC.