首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在golang中处理没有时间的日期的惯用方法是什么?

在golang中处理没有时间的日期的惯用方法是什么?
EN

Stack Overflow用户
提问于 2015-02-11 12:49:11
回答 2查看 15.1K关注 0票数 22

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

它是以"2006-01-02“格式传入和传出服务器的JSON数据,这些数据使用日期列与mysql数据库通信。

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

代码语言:javascript
复制
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%来表示date类型。

上面的代码可以工作,但我觉得我是在与Go的潮流作斗争。因此,对于熟悉该语言的人来说,有几个问题要提:

你认为这段代码会带来比节省更多的痛苦吗?

如果有,你会推荐哪种风格?

EN

回答 2

Stack Overflow用户

发布于 2020-05-20 07:41:20

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

票数 5
EN

Stack Overflow用户

发布于 2015-03-29 08:54:30

我认为您可以将数据存储为time.Time,但将其转换为字符串用于JSON目的:

代码语言:javascript
复制
type LocalDate struct {
  t time.Time `json:",string"` // might even work anonymously here
}

要了解如何使用SQL执行此操作:https://github.com/go-sql-driver/mysql#timetime-support

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28446796

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档