Golang 时间类型前后端转换错误 datetime-local转为time.Time
错误:
前端传回 datetime-local 在使用gorm的ShouldBindJSON方法转为 结构体的time.Time类型时出错 “error”: "parsing time “2024-07-06T23:16” as "2006-01-02T15:04:05Z07
解决方法示例:
<input type="datetime-local" id="birth_date" placeholder="Birth Date">
async function create() {
const student = {
birth_date: document.getElementById('birth_date').value ? new Date(document.getElementById('birth_date').value).toISOString() : null
};
const response = await fetch(`${baseURL}/pets`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(pet)
});
const data = await response.json();
console.log(data);
}
在Go语言中,time.Time类型默认使用RFC3339格式化日期和时间。RFC3339是ISO 8601的一个子集,因此在处理时间时可以互换使用。
为了确保在前端发送的数据符合RFC3339格式,可以使用JavaScript的toISOString()方法来转换日期时间值。使用**new Date(value).toISOString()**来转换输入的日期时间值为RFC3339格式。如果值为空,则设置为null。
gorm 更新数据库允许字段为空的两种方法
在结构体中,如果某个字段的值允许为空,在插入数据库或者更新时,可以使用两种方法:
type Person struct {
ID int64 `gorm:"primaryKey;autoIncrement;comment:'ID'" json:"id"`
Name string `gorm:"column:name;type:varchar(100);not null;comment:'名字'" json:"name"`
// 方法一:使用*加类型
Description *string `gorm:"column:description;type:text;comment:'描述'" json:"description"`
CreatedAt time.Time `gorm:"column:created_at;type:datetime;comment:'创建时间'" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at;type:datetime;comment:'更新时间'" json:"updated_at"`
// 方法二,使用gorm标签,设置默认值default:null
DeletedAt time.Time `gorm:"column:deleted_at;type:datetime;default:null;comment:'删除时间'" json:"deleted_at"`
IsDelete bool `gorm:"column:is_delete;type:bit(1);default:0;comment:'是否删除,0为未删除,1为已删除'" json:"is_delete"`
}
- 使用指针类型(*type)来表示可空字段。
- 使用gorm标签default:null表示在数据库中插入时该字段的默认值为NULL。
具体的区别和注意事项如下:
-
使用指针类型表示可空字段:这种方法比较直接,可以区分字段是否有值。未设置值的指针类型字段会被序列化为null。
-
使用gorm标签default:null:这种方法在数据库层面上设置了默认值为NULL,但是在Go代码中并没有明确地表示这个字段可能为空。通常结合使用零值和数据库默认值。