我在 SQLite 資料庫中有一個DATESequelize 型別的列:
modified:{ type: DataTypes.DATE }
就在保存物件之前,我得到“現在”的日期,如下所示:
object.modified = new Date()
await MyType.upsert(object)
到目前為止,一切看起來都很好,但是當我在 SQLite 查看器應用程式中查看資料時,我看到了這種日期格式:
//JavaScript date Format in SQLite
2022-06-14 18:52:44.816 00:00
...但為了使其與我相應的 Swift 應用程式兼容,我需要它采用以下格式:
//Swift date format in SQLite
2022-06-14T18:52:44.816
我發現在我的 JS 應用程式中獲得相同格式的唯一方法是將日期保存為帶有Day.jsdayjs(new Date()).format('YYYY-MM-DD[T]HH:mm:ss[.]SSS')的字串,如下所示:
如何DATE在 SQLite 中為 Sequelize 設定自定義日期格式?
uj5u.com熱心網友回復:
Sequelize 的 DATE 資料型別默認為該日期 時間 偏移格式。如果您有您希望在資料庫軟體中使用的日期格式(開箱即用或自定義創建),您可以擴展 Sequelize 的 datatypes。這是相對輕松的代碼來實作。
uj5u.com熱心網友回復:
我昨晚開始寫我的問題,今天想出了一個潛在的解決方案,所以我想我會分享它。這可能不是正確的方法,但它似乎有效。
為了讓我的日期列具有自定義格式,我可以在我的資料型別定義中modified使用Sequelize getter 和 setter 。
import { Sequelize, DataTypes, Model } from 'sequelize'
import dayjs from 'dayjs'
modified: {
type: DataTypes.STRING,
//Whenever modified is retrieved from the DB, format the string to a date object
get(){
return dayjs(this.getDataValue('modified'), 'YYYY-MM-DD[T]HH:mm:ss[.]SSS')
},
//Whenever modified is saved, format the date object to my custom string format
set(value){
this.setDataValue('modified', dayjs(value).format('YYYY-MM-DD[T]HH:mm:ss[.]SSS'))
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494378.html
