dpymrcl269187540 2015-02-11 04:49
浏览 96

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

I'm writing a REST API in Go, working with dates that don't represent a single point in time.

It's JSON data going to and from the server in "2006-01-02" format, with that data talking to a mysql database using DATE columns.

One thing I've tried is to create a struct that embeds a Time, and implements JSON and SQL conversion interface implementations to be able to correctly interact with the endpoints while still having Time methods available for date math and formatting. e.g.:

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)
}

And then other structs can be of this type, and get 90% there to representing the date type in my problem domain.

The above code works, but I feel like I'm fighting against the Go current. So a couple questions for the veterans of the language:

Do you think this code will cause more pain than it'll save?
If so, what style would you recommend?

  • 写回答

1条回答 默认 最新

  • dongren4099 2015-03-29 00:54
    关注

    I think you can store your data as time.Time but convert it to a string for JSON purposes:

    type LocalDate struct {
      t time.Time `json:",string"` // might even work anonymously here
    }
    

    To see how to make this work with SQL: https://github.com/go-sql-driver/mysql#timetime-support

    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决