简体   繁体   中英

How to convert Swift Date or String to timestamp without time zone of PostgreSQL?

I am using Vapor 3, Swift 5.1, PostgreSQL 12, and Postico 1.5.10 for my Backend. In the PostgreSQL database, there is a field with the name eventDate of type timestamp without time zone . Please, look at screenshot:

在此处输入图片说明

In Vapor, there is a model:

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

But when I am trying to save Date (Swift) to timestamp without time zone Vapor gives me error:

[ ERROR ] DecodingError.typeMismatch: Value of type 'String' required for key 'eventDate.date'. (NIOServer.swift:104)

If, in model, I am changing Date to String , Vapor gives me this error:

[ ERROR ] PostgreSQLError.server.error.transformAssignedExpr: column "eventDate" is of type timestamp without time zone but expression is of type text (NIOServer.swift:104)

So the question is: how to transfer Date and String to timestamp without time zone (or timestamp with time zone )?

I will be thankful for any help or advice!

why do you save time stamps without a time zone? time stamp without a time zone is not a date - it is a string.

any way - you just have to init a time format without a time zone, then just use it to get a string.

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

It's no 100% solution I wanted but it's also very good.

import Vapor
import FluentPostgreSQL

final class TestModel: PostgreSQLModel {

    static var createdAtKey: TimestampKey? = \.createdAt

    var id: Int?
    var someValue: Int
    var someOtherProprty: String
    var createdAt: Date?

    init(someValue: Int, someOtherProprty: String) {
        self.someValue = someValue
        self.someOtherProprty = someOtherProprty
    }

}

extension TestModel: Content {
}

extension TestModel: Migration {
}

extension TestModel: Parameter {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM