登录
首页 >  Golang >  Go问答

如何在Golang中表示MySQL中的time数据类型?

来源:stackoverflow

时间:2024-03-15 17:18:31 184浏览 收藏

在 Go 中表示 MySQL 的 time 数据类型时,如果 MySQL 表中将 time 数据类型从 timestamp 更改为 time,则 Go 中的结构体应将 starttime 和 endtime 更改为 []byte 类型。通过自行解析,可以将 []byte 转换为 time.Time 类型。

问题内容

我有一个 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 的原因是我只需要时间,而不需要日期信息。

有什么好的建议吗?


正确答案


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

你可以这样做:

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

理论要掌握,实操不能落!以上关于《如何在Golang中表示MySQL中的time数据类型?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>