等MongoDB中我有存儲此Date對象日期:貓鼬.find是給我的一個格式錯誤
"$date": "2015-08-27T13:50:49.000Z"
所以有關MongoDB的日期是正確的。然後,我使用的是貓鼬.find()
獲得在該數據庫中像這樣的「最新」消息:
Message.find({}).sort({ "created_at" : -1 })
.limit(1)
.exec(function(error, result) {
if(error) callback(error);
var date = moment(result.created_at);
console.log(date);
console.log(result);
callback(null, result);
});
所以,當我登錄result
到控制檯,這是消息本身,它爲我的時間,因爲這:
created_at: Thu Aug 27 2015 21:50:49 GMT+0800 (CST)
的時間是正確的,但我不希望接收時,它顯然是存儲在MongoDB中爲UTC日期爲北京時間。在這個具體的例子,moment(result.created_at)
打印日期安慰這樣的:
{ [Number: 1440685886247]
_isAMomentObject: true,
_isUTC: false,
_locale:
{ _ordinalParse: /\d{1,2}(th|st|nd|rd)/,
ordinal: [Function],
_abbr: 'en',
_ordinalParseLenient: /\d{1,2}(th|st|nd|rd)|\d{1,2}/ },
_d: Thu Aug 27 2015 22:31:26 GMT+0800 (CST) }
不知怎的,根據我的筆記本電腦,這是實際打印當前時間。我不知道爲什麼使用MongoDB中的日期date
被宣佈爲moment()
。
那麼有誰知道我可以如何成功地使用我的數據庫中的日期?當將消息打印到控制檯時,我將它打印成格林尼治標準時間,並且在使用筆記本時似乎正在打印筆記本電腦的時間。
謝謝!
更新:
到目前爲止,我已經嘗試從數據庫中取result.created_at
並輸出使用以下方法來安慰:
var date = Date(result.created_at) // Prints current time on laptop
var date = new Date(result.created_at) // Prints undefined
var date = result.created_at // Prints undefined
var date = moment(result.created_at) // Prints moment object with the time as computer's time
我有點卡住了。我想用這個日期對象作爲另一個函數,但只能讓它保存電腦的時間。
那麼在'console.log()''Date'對象中只需進行字符串化。 Date的默認'.toString()'方法產生你所看到的本地時間字符串。 「實際」日期對象通常是您期望的UTC值。所以你的「時刻」調用應該期望一個JavaScript Date對象,而不是像你所做的那樣是一個「字符串」。 –
有趣的是,你如何建議我從數據庫中獲取'Date',並獲得它的'String'等價關係以便我可以使用它?基本上我需要它作爲一個字符串,以便我可以使用它進行API請求。當記錄'moment(result.created_at)'它也顯示當地時間?儘管它是直接從'.find()'傳遞的Date對象。感謝您在過去幾天對我的問題的回覆,我絕對不是Mongoose/MongoDB上最知名的人,我更像是一名設計/前端人! – germainelol
你需要在這裏瞭解更多。我給你幾次幫助,但不斷學習。你做錯了事。學習正確的方法。這是「不發送條紋」。對外部API使用「時間戳」,它們都知道如何處理任何語言的數據。 –