我在后端使用Vapor 3,Swift 5.1,PostgreSQL 12和Postico 1.5.10。在PostgreSQL数据库中,有一个名称为eventDate
且类型为timestamp without time zone
的字段。请看截图:
在蒸气中,有一个模型:
import Vapor
import FluentPostgreSQL
final class TestModel: PostgreSQLModel {
var id: Int?
var eventDate: Date
init(eventDate: Date) {
self.eventDate = eventDate
}
}
extension TestModel: Content {
}
extension TestModel: Migration {
}
extension TestModel: Parameter {
}
但是当我尝试将Date
(Swift)保存为timestamp without time zone
时,蒸气给了我错误:
[ ERROR ] DecodingError.typeMismatch: Value of type 'String' required for key 'eventDate.date'. (NIOServer.swift:104)
如果在模型中,我将Date
更改为String
,蒸气会给我这个错误:
[ ERROR ] PostgreSQLError.server.error.transformAssignedExpr: column "eventDate" is of type timestamp without time zone but expression is of type text (NIOServer.swift:104)
所以问题是:如何将Date
和String
传输到timestamp without time zone
(或timestamp with time zone
)?
感谢您的帮助或建议!
为什么您保存没有时区的时间戳?没有时区的时间戳记不是日期-它是一个字符串。
任何方式-您只需要初始化一个没有时区的时间格式,然后使用它来获取字符串即可。
let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: Date())