donglu3184 2019-08-03 16:00
浏览 12


I'm using GORM to retrieve data from a Postgresql database. Inside the postgresql database I'm storing times as the default UTC. When I load them through gorm/golang I would like to automatically convert them to 'Europe/London' location.

Currently, all times are returned as my local timezone (CEST). I'm struggling to find a way to manually override this?

Here is the relevant code:

type Booking struct {
    Service   Service
    ServiceID uint `json:serviceId`
    Start     time.Time
    Finish    time.Time

func getBookings() http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        bookings := &[]Booking{}


        render.JSON(w, r, bookings)

I've been looking around and I can't seem to find any information from gorm or golang docs. The two closest things to mentions of this problem that I've found is:

Setting timezone globally in golang

I thought a work around could be to manually change the query results with a loop, but I'm not sure if this is the most efficient solution? - code below:

func getBookings() http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        bookings := &[]Booking{}
        timeZoneBookings := *&[]Booking{}


        for _, booking := range *bookings {

            booking.Start = parseToUkTime(booking.Start)
            booking.Finish = parseToUkTime(booking.Finish)

            timeZoneBookings = append(timeZoneBookings, booking)


        render.JSON(w, r, timeZoneBookings)

func parseToUkTime(timeToParse time.Time) time.Time {
    loc, _ := time.LoadLocation("Europe/London")

    t := timeToParse.In(loc)

    return t


Here is an image of the DB entry:

enter image description here

I assumed it would be easy to either state inside the type I would like the location to be set to Europe/London so the struct would automatically be populated this way, however this doesn't seem to be the case? It's the first time I have worked with timezones, so everything is quite confusing.

  • 写回答

1条回答 默认 最新


      相关推荐 更多相似问题


      • ¥15 edge跟谷歌浏览器的默认搜索引擎无法修改,如何解决?
      • ¥15 access数据库出错
      • ¥100 matlab数学建模习题,求解答
      • ¥15 blender python输出纹理坐标(像素级)与三维坐标的对应关系
      • ¥15 python文件分发
      • ¥15 关于#c语言#的问题:要求:输出格式要界面直观、清晰大方、格式规范
      • ¥15 计算机组成汇编语言电路升级
      • ¥15 hadoop网站点击流数据分析项目
      • ¥15 TDA4 USB 识别不到的问题
      • ¥36 禁用ssl重协商以达到解决DOS漏洞