Golang Xgorm 查询 MySQL timestamp 字段并返回 yyyy-mm-dd hh:ii:ss 格式 JSON 数据
在 Golang 中,可以使用 time.Time 类型来表示 MySQL 的 timestamp 字段。要将时间格式化为'yyyy-mm-dd hh:ii:ss' 的格式,可以使用 time.Time 的 Format 方法。下面是一个示例代码,演示了如何使用 xgorm 查询 MySQL 的 timestamp 字段,并将结果以'yyyy-mm-dd hh:ii:ss' 的格式返回为 JSON。
package main
import (
"encoding/json"
"fmt"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
ID uint `gorm:"primary_key" json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at"`
}
func main() {
dsn := "user:password@tcp(localhost:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
var users []User
if err := db.Find(&users).Error; err != nil {
panic(err)
}
for _, user := range users {
user.CreatedAt = user.CreatedAt.Local() // 转换为本地时间
user.UpdatedAt = user.UpdatedAt.Local()
user.DeletedAt = user.DeletedAt.Local()
}
jsonBytes, err := json.MarshalIndent(users, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(jsonBytes))
}
在上面的代码中,我们首先定义了一个 User 结构体,其中 CreatedAt, UpdatedAt 和 DeletedAt 字段的类型为 time.Time,用于表示 MySQL 的 timestamp 字段。然后,我们使用 gorm 进行数据库查询,并将查询结果保存在 users 切片中。
接下来,我们遍历 users 切片,使用 Local() 方法将 CreatedAt, UpdatedAt 和 DeletedAt 转换为本地时间。然后,我们使用 json.MarshalIndent 将 users 切片转换为 JSON 格式的字节数组。
最后,我们使用 fmt.Println 打印 JSON 字符串。
请注意,上述代码中的 dsn 变量应替换为您自己的 MySQL 连接字符串。
原文地址: https://www.cveoy.top/t/topic/qk7p 著作权归作者所有。请勿转载和采集!