问题

在使用 gorm 的过程中, 处理时间戳字段时遇到问题。写时间戳到数据库时无法写入。

通过查阅资料最终问题得以解决,特此总结

设置数据库的 dsn

parseTime = "True"

loc = "Local"

设置自定义 Time 类型

package types

import (
"database/sql/driver"
"fmt"
"time"
) // Time is alias type for time.Time
type Time time.Time const (
timeFormart = "2006-01-02 15:04:05"
zone = "Asia/Shanghai"
) // UnmarshalJSON implements json unmarshal interface.
func (t *Time) UnmarshalJSON(data []byte) (err error) {
now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), time.Local)
*t = Time(now)
return
} // MarshalJSON implements json marshal interface.
func (t Time) MarshalJSON() ([]byte, error) {
b := make([]byte, 0, len(timeFormart)+2)
b = append(b, '"')
b = time.Time(t).AppendFormat(b, timeFormart)
b = append(b, '"')
return b, nil
} func (t Time) String() string {
return time.Time(t).Format(timeFormart)
} func (t Time) local() time.Time {
loc, _ := time.LoadLocation(zone)
return time.Time(t).In(loc)
} // Value ...
func (t Time) Value() (driver.Value, error) {
var zeroTime time.Time
var ti = time.Time(t)
if ti.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return ti, nil
} // Scan valueof time.Time 注意是指针类型 method
func (t *Time) Scan(v interface{}) error {
value, ok := v.(time.Time)
if ok {
*t = Time(value)
return nil
}
return fmt.Errorf("can not convert %v to timestamp", v)
}

这样程序中所有的时间值都使用types.Time类型就可以准确进行时间戳变量的读写操作。

原理

其实就是自定义数据库数据类型,在 sql driver 中实现自定义类型需要实现 ScannerValuer接口

Scanner

type Scanner interface {
Scan(src interface{}) error
}

Valuer

type Valuer interface {
// Value returns a driver Value.
Value() (Value, error)
}

unmarshalmarshal 自定义 json 转换格式

参考

https://reading.developerlearning.cn/discuss/2019-06-19-gorm-mysql-timestamp/

gorm 处理时间戳的更多相关文章

  1. gorm的日志模块源码解析

    gorm的日志模块源码解析 如何让gorm的日志按照我的格式进行输出 这个问题是<如何为gorm日志加traceId>之后,一个群里的朋友问我的.如何让gorm的sql日志不打印到控制台, ...

  2. gorm中数据库datetime类型的映射和time.Time的格式化

    如果在结构体中设置time变量的类型是time.Time,那么gorm取出来的时间格式将会是”2006-01-02 15:04:05.999999999 -0700 MST“东八区时间,在time.T ...

  3. go 学习之gorm

    gorm是一个饱受好评的orm框架,此处数据库我们以mysql为例 import ( "github.com/jinzhu/gorm" _ "github.com/jin ...

  4. GORM入门指南

    gorm是一个使用Go语言编写的ORM框架.它文档齐全,对开发者友好,支持主流数据库. gorm介绍 Github GORM 中文官方网站内含十分齐全的中文文档,有了它你甚至不需要再继续向下阅读本文. ...

  5. GORM CRUD指南

    CRUD通常指数据库的增删改查操作,本文详细介绍了如何使用GORM实现创建.查询.更新和删除操作. CRUD CRUD通常指数据库的增删改查操作,本文详细介绍了如何使用GORM实现创建.查询.更新和删 ...

  6. Go ORM框架 - GORM 踩坑指南

    今天聊聊目前业界使用比较多的 ORM 框架:GORM.GORM 相关的文档原作者已经写得非常的详细,具体可以看这里,这一篇主要做一些 GORM 使用过程中关键功能的介绍,GORM 约定的一些配置信息说 ...

  7. GORM学习指南

    orm是一个使用Go语言编写的ORM框架.它文档齐全,对开发者友好,支持主流数据库. 一.初识Gorm Github GORM 中文官方网站内含十分齐全的中文文档,有了它你甚至不需要再继续向下阅读本文 ...

  8. gorm声明模型

    模型定义 模型是标准的结构体,由go的基本数据类型.实现了Scanner和Valuer接口的自定义类型及其指针或别名组成 例如: type User struct { ID uint Name str ...

  9. gorm连接mysql和模型定义那些事

    1. gorm操作mysql: 1.1 安装gorm gorm官网: https://gorm.io/zh_CN/docs/connecting_to_the_database.html gorm的g ...

随机推荐

  1. C# 监测每个方法的执行次数和占用时间(测试5)

    又找到了一个bug 测试的类: public class Class11_1 { public virtual List<int> test2_1(List<tb_SensorRec ...

  2. 51Nod 1769 Clarke and math2

    51Nod 1769 Clarke and math2 http://www.51nod.com/Challenge/Problem.html#!#problemId=1769 要算的是\(G=F*I ...

  3. 利用Python进行数据分析【第二版】【高清中文版英文版源代码】

    如果被河蟹请回复我更新链接   这是我花钱弄的,免费分享给大家.没有密码,直接可以观看!   希望大家不要拿去后再做收费分享   如果好用,请给个赞好嘛~~~   1.中文pdf 链接:https:/ ...

  4. x32下的DLL隐藏

    原理主要就是PEB 中模块断链. 这里整理下代码.原理可以看下另一篇我写的帖子. https://www.cnblogs.com/iBinary/p/9601860.html // dllmain.c ...

  5. mysql帐号,权限管理

    -> use mysql; //选择数据库 -> select host,user,password from user; //查询已有用户 -> insert into user ...

  6. Spring Boot 配置文件 bootstrap vs application 到底有什么区别?

    用过 Spring Boot 的都知道在 Spring Boot 中有以下两种配置文件 bootstrap (.yml 或者 .properties) application (.yml 或者 .pr ...

  7. 学习opencv(1)

    目录 CV_8UC3 Scalar--颜色赋值 using namespace cv找不到命名空间 waitKey() getTickCount() 引用 CV_8UC3 a) 存放单通道图像中像素: ...

  8. uniapp - 阿里图库字体图标使用

    [iconfont下载] https://www.iconfont.cn/search/index?searchType=icon&q=%E4%B8%8A%E4%BC%A0 可能报错,找不到线 ...

  9. axios 文件下载代码 片段

    <script type="text/javascript"> axios({ method:'post', url: 'url', // 最好qs.stringify ...

  10. LC 968. Binary Tree Cameras

    Given a binary tree, we install cameras on the nodes of the tree. Each camera at a node can monitor  ...