在Golang中,与MySQL的`time`类型对应的结构是`time.Time`。

huangapple go评论84阅读模式
英文:

What is the golang structure corresponding to `time` type in mysql?

问题

我有一个存储类似闹钟的定时任务的MySQL表。

表的结构设计如下:

在MySQL中:

CREATE TABLE if not EXISTS `tasks`
(
    //....其他字段
    `start_time`  timestamp NOT NULL ,
    `end_time`    timestamp NOT NULL ,
)

在Golang中:

type Tasks struct {
    //....其他字段
	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`
(
    //....其他字段
    `start_time`  time NOT NULL ,
    `end_time`    time NOT NULL ,
)

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

我想将timestamp更改为time的原因是我只需要时间信息,而不需要日期信息。

有什么好的建议吗?

英文:

I have a mysql table that stores scheduled tasks like an alarm clock.

The representation is designed like this:

In mysql:

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

In golang:

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

What I want to ask is suppose I change the tasks table in mysql to look like this:

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

How should my Tasks structure be designed in Golang?

The reason WHY I want to change timestamp to time is that I only need the time, not the date information.

Any good suggestions?

答案1

得分: 1

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

你可以这样做:

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

I think you'll need to change StartTime and EndTime to []byte and parse this yourself to get a time.Time type.

You could do something like:

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

huangapple
  • 本文由 发表于 2021年9月9日 16:17:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/69114635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定