iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 28
1
自我挑戰組

I Shot You 不小心系列 第 28

Mongoose Schema TimeZone

關於 時區

因為取資料的方式都以時間線的方式取得(http, websocket)

所以時區是一個必須要解決的問題

在 Mongodb 中 Date 儲存的是 Int

沒有辦法在 Storage 層中解決時區問題

所以在儲存的時候都統一使用 UTC

所以在處理時區問題可以在 getter/setter 中解決

以getter 做範例

const DEFAULT_TIME_ZONE = 'Asia/Taipei';
const DEFAULT_FORMAT_DATE_TIME = 'yyyy-MM-dd HH:mm:ss.SSS';

const schemaOptions = {
  toObject: {
    getters: true,
    virtuals: true,
    versionKey: false,
    transform: function(doc, ret) {
      ret.id = ret._id;
      delete ret._id;
    }
  },
  toJSON: {
    getters: true,
    virtuals: true,
    versionKey: false,
    transform: function(doc, ret) {
      ret.id = ret._id;
      delete ret._id;
    }
  },
  runSettersOnQuery: true,
};

const formatDateTime = (date) =>
  format(utcToZonedTime(date, DEFAULT_TIME_ZONE), DEFAULT_FORMAT_DATE_TIME);


const messageSchema = new Schema({
  createAt: {
    type: Date,
    default: now,
    get: formatDateTime,
  },
}, schemaOptions);

這樣取值的時候會自動將 UTC 轉為 Asiz/Taipei 的時區時間

再順便處理 format

而在 schemaOptions 中部只處理 getter/setter

同時將 _id => id 做處理

參考資料

UTC與 GTM


上一篇
React Native Fastlane
下一篇
倒數第二天
系列文
I Shot You 不小心30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言