【问题标题】:What is the golang structure corresponding to `time` type in mysql?mysql中`time`类型对应的golang结构是什么?
【发布时间】:2021-11-05 21:50:46
【问题描述】:

我有一个 mysql 表,用于存储计划任务,例如闹钟。

表示是这样设计的:

在 mysql 中:

CREATE TABLE if not EXISTS `tasks`
(
    //....other fields
    `start_time`  timestamp NOT NULL ,
    `end_time`    timestamp NOT NULL ,
)

在 golang 中:

type Tasks struct {
    //....other fields
    StartTime  time.Time `json:"start_time" xorm:"start_time"`
    EndTime    time.Time `json:"end_time" xorm:"end_time"`
}

我想问的是假设我将 mysql 中的 tasks 表更改为如下所示:

CREATE TABLE if not EXISTS `tasks`
(
    //....other fields
    `start_time`  time NOT NULL ,
    `end_time`    time NOT NULL ,
)

我的Tasks 结构应该如何在 Golang 中设计?

我之所以要将timestamp 更改为time,是因为我只需要时间,而不需要日期信息。

有什么好的建议吗?

【问题讨论】:

  • 请勿发布文字图片。
  • 为什么会这样?如何在不使用图像的情况下突出显示这两个字段?@Volker
  • @ClancyZeng 尝试使用pgtype.Time,虽然它是 PostgreSQL 特定的实现,但在我看来 MySQL 时间类型表示与 PostgreSQL 兼容。
  • @ClancyZeng “突出显示”这两个字段的一种方法是简单地删除与您的问题无关的所有字段。

标签: mysql go


【解决方案1】:

我认为您需要将 StartTimeEndTime 更改为 []byte 并自行解析以获得 time.Time 类型。

你可以这样做:

type sqlTime []byte
func (s sqlTime) Time() (time.Time, error) {
    return time.Parse("15:04:05",string(s))
}

【讨论】:

  • 喜欢这个? ``` type Tasks struct { //....其他字段 StartTime sqlTime json:"start_time" xorm:"start_time" EndTime sqlTime json:"end_time" xorm:"end_time" } ``
  • 应该可以工作,如果你想将它用作时间类型,只需调用 sqlTime.Time()
  • 好的,谢谢,如果没有更好的办法,我会考虑使用你的答案。
猜你喜欢
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
  • 2011-12-11
  • 1970-01-01
  • 2019-08-27
  • 2015-09-18
  • 1970-01-01
  • 2021-12-20
相关资源
最近更新 更多