問題描述
MongoDB/Mongoose 時區日期遞減問題 (MongoDB/Mongoose timezone date decrement problem)
我有一個帶有“日期”的編輯頁面。類型輸入。我正在使用 node.js、express 和 mongoose 來提取輸入內容,並使用 Mongoose 模型中的日期字段將其保存到數據庫中。當我在進入數據庫之前記錄日期時,我看到的是:2020‑03‑31
。當我在數據庫中查看它時,我看到的是:2020‑03‑31T00:00:00.000+00:00
。+00:00 是否意味著它正在分配時區?我是否需要編輯我的 MongoDB 數據庫存儲日期的方式?
當我讀回時區並使用它來填充編輯頁面上的輸入時,我遇到了時區問題。我正在使用 Mongoose 模型函數在日期進入 html 輸入的值字段之前對其進行格式化。在那個函數中,我' m 運行以下代碼:
console.log(date);
// Output:
// 2020‑03‑31T00:00:00.000Z
console.log(date.getDate());
// Output:
// 30
“Z”是否來自“+00:00”?以上?我是 GMT‑4,所以我的服務器將那個時間解釋為 3 月 30 日晚上 8 點,現在編輯頁面上的日期選擇器填充了 3 月 30 日而不是 31 日。如果我保存它,那麼下次我加載頁面時,輸入將顯示為 3 月 29 日。我不想在每次加載和保存頁面時無意中將日期減一!
在這種情況下,我真的不在乎時間,只想參考日期。我可以在這裡使用不同的最佳做法嗎?
所以我的服務器將那個時間解釋為 3 月 30 日晚上 8 點,現在編輯頁面上的日期選擇器填充了 3 月 30 日而不是 31 日。如果我保存它,那麼下次我加載頁面時,輸入將顯示為 3 月 29 日。我不想在每次加載和保存頁面時無意中將日期減一!在這種情況下,我真的不在乎時間,只想參考日期。我可以在這裡使用不同的最佳做法嗎?
所以我的服務器將那個時間解釋為 3 月 30 日晚上 8 點,現在編輯頁面上的日期選擇器填充了 3 月 30 日而不是 31 日。如果我保存它,那麼下次我加載頁面時,輸入將顯示為 3 月 29 日。我不想在每次加載和保存頁面時無意中將日期減一!在這種情況下,我真的不在乎時間,只想參考日期。我可以在這裡使用不同的最佳做法嗎?
參考解法
方法 1:
MongoDB stores timestamps only, it does not have a facility to store dates. Javascript similarly does not have a facility for storing dates natively contrary to what you might expect ‑ the Date type is actually a DateTime. Mongoose also does not have a date type (it uses JS Date which is a datetime).
What this means is:
- When you are converting user input to a JS Date instance, you are getting the date converted to a datetime (sounds like the time component is zero in UTC in your application).
- When you are reading the date out of the database, you are reading a datetime (which is the beginning of the day of that date in UTC per your provided information, not in your local time).
I would then proceed as follows:
- The DateTime you are reading is the beginning of day on your date in UTC.
- If mongoose converts the time to your local time, as it appears to do, you need to either stop it from doing that or convert back to UTC.
- Then retrieve the year‑month‑day components of the UTC datetime.
- Using these components you can create a new Date instance in local time or do whatever else you wish such as rendering them.
There are various libraries available in JS for dealing with dates and time zones, but the language itself has limited date support.