date - 在golang中使用没有时间的日期的惯用方式是什么?

标签 date go

我正在用 Go 编写一个 REST API,使用不代表单个时间点的日期。

它是以“2006-01-02”格式进出服务器的 JSON 数据,该数据使用 DATE 列与 mysql 数据库通信。

我尝试过的一件事是创建一个嵌入 Time 的结构,并实现 JSON 和 SQL 转换接口(interface)实现,以便能够正确地与端点交互,同时仍然具有可用于日期数学和格式化的 Time 方法。例如:

package localdate

import (
    "time"
    "encoding/json"
    "database/sql/driver"
)

type LocalDate struct {
    time.Time
}

func NewLocalDate(year int, month time.Month, day int) LocalDate {
    time := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
    return LocalDate{Time: time}
}

const LocalDateFormat = "2006-01-02" // yyyy-mm-dd

func (ld *LocalDate) UnmarshalJSON(data []byte) error {
    // parse and set the ld.Time variable
}

func (ld *LocalDate) MarshalJSON() ([]byte, error) {
    return json.Marshal(ld.Format(LocalDateFormat))
}

// sql.Scanner implementation to convert a time.Time column to a LocalDate
func (ld *LocalDate) Scan(value interface{}) error {}

// sql/driver.Valuer implementation to go from LocalDate -> time.Time
func (ld *LocalDate) Value() (driver.Value, error)  {}

// used to convert a LocalDate into something we can plug into a query
// we could just use ld.Time, but that would send '2015-01-01 00:00:00 +0000 UTC'
// instead of '2015-01-01' for the DATE query parameter.  (Which works for mysql, but is officially invalid SQL)
func (ld *LocalDate) SqlDate() string  {
    return ld.Format(LocalDateFormat)
}

然后其他结构可以是这种类型,并在那里获得 90% 来表示我的问题域中的日期类型。

上面的代码有效,但我觉得我正在与 Go 潮流作斗争。所以有几个问题要问语言的老手:

你认为这段代码会带来比它所节省的更多的痛苦吗?
如果有,你会推荐什么风格?

最佳答案

我使用包中的 civil.Date cloud.google.com/go/civil

关于date - 在golang中使用没有时间的日期的惯用方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28446796/

相关文章:

excel - 将日期格式更改为 yyyy-mm-dd

c - C 中日期的奇怪行为

macos - 使用 brew 安装 go,并运行 gotour

Java 文件最后一次修改是在默认时区吗?

php - 将日期格式转换为mysql时间戳

android - 月、日的日期差异

go - 在1页中将相同的模板与不同的参数/变量一起使用

Go:内存问题

google-app-engine - Go 应用引擎 dev_appserver.py 不支持运行时 go112

linux - 如何创建在每个发行版上运行的静态 Go 二进制文件?