【问题标题】:How can specify time location for CreatedAt when selecting results?如何在选择结果时为 CreatedAt 指定时间位置?
【发布时间】:2023-02-08 05:33:12
【问题描述】:

我有一个表,其中 Created_At 字段为“带时区的时间戳”

当我选择行时,我有带有 CreatedAt 的实体和我所在位置的时区,我想将其设置为 UTC。

    type app struct {
    ID        uuid.UUID
    CreatedAt time.Time
    }

    db, err := gorm.Open(
    postgres.Open(databaseURL),
    &gorm.Config{},
    )
    if err != nil {
    panic(err)
    }

    a := &app{}
    db.Table("applications").Take(a)
    fmt.Println(a.CreatedAt)

它打印“2023-02-01 11:26:29.554589 +0300 MSK” 我想要“2023-02-01 08:26:29.554589 +0000 UTC”

有一些选择吗(gorm-v2)?

顺便说一句,gorm-v1 检索为 UTC。和 gorm-v2 - 在当前位置

【问题讨论】:

    标签: timezone go-gorm


    【解决方案1】:

    我不确定你为什么使用带时区的时间戳,但这里有一些解决这个问题的方法。我发现有用的解决方案 (see here) 是在连接到数据库时提供一个 NowFunc:

    db, err := gorm.Open(postgres.Open(connectionString), &gorm.Config{
                Logger: logger.Default.LogMode(logger.Info),
                NowFunc: func() time.Time {
                    utc, _ := time.LoadLocation("")
                    return time.Now().In(utc)
                },
            })
    

    然后你可以看到你的数据是按照你的表规范保存的,并且按照你在 Go 中的预期显示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 2011-09-08
      • 2022-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多