[英]How do I format dates from Mongoose in Node.js?
我正在嘗試更改從我的 Mongo 數據庫中獲取的日期格式。 目前他們看起來像這樣:
Fri Sep 16 2011 19:05:17 GMT+0900 (JST)
我試過對它們調用.toString('yyyy-MM-dd')
但沒有任何變化。 我不知道它們是Date
對象還是只是原始字符串。
我試過檢查 Mongoose 手冊並用谷歌搜索了一堆,但還沒有找到任何東西。
有任何想法嗎?
一種現代方法是使用momentjs ,既可在節點中使用,也可在瀏覽器中使用,超級有用且易於使用。 對於當前的問題,我在遵循所有文檔要求后在節點中解決了這個問題:
var moment = require('moment');
var fomatted_date = moment(photo.date_published).format('YYYY-MM-DD');
photo.date_published
直接來自貓鼬。
你必須先創建一個 Date 對象:
var date = new Date(dateStr); // dateStr you get from mongodb
var d = date.getDate();
var m = date.getMonth()+1;
// ...
定義你的架構怎么樣:
var someSchema = new Schema({
title: String,
created: Date
});
st 日期作為Date
對象存儲在您的 mongoDB 中。 因此,當您回讀它時,您將擁有一個合適的Date
對象,您可以在該對象上使用可用的方法。
只需簡單添加
date: { type: String, default: Date }
輸出將是:{“日期”:“2020 年 11 月 28 日星期六 22:57:38 GMT+0530(印度標准時間)”}
created_at:{ type:Date, default:Date.now } 為當前日期和時間添加這個簡單的行
輸出:----- 2021 年 7 月 2 日星期五 10:45:26 GMT+0530(印度標准時間)
我傾向於做的是,在模式中,我用Date類型定義日期:
const exampleSchema = new mongoose.Schema({
startDate: {
type: Date,
required: true // or false, depending upon needs (plus other options, as needed)
},
endDate: {
type: Date,
required: true // or false, depending upon needs (plus other options, as needed)
},
whateverDate: {
type: Date,
required: true // or false, depending upon needs (plus other options, as needed)
}
});
然后我為 mongoose 模式定義了一個實例方法:
// Returns a date in 'yyyy-MM-dd' format
exampleSchema.methods.formatDate = function(datePropery) {
const newDate = new Date(this[dateProperty]);
let formattedDate = `${ newDate.getFullYear() }-`;
formattedDate += `${ `0${ newDate.getMonth() + 1 }`.slice(-2) }-`; // for double digit month
formattedDate += `${ `0${ newDate.getDate() }`.slice(-2) }`; // for double digit day
return formattedDate;
}
並且,定義 mongoose model:
const Example = new mongoose.model('Example', exampleSchema);
后來,在我選擇了一個特定的實例之后(對我來說這通常在異步函數中),例如
const item = await Example.findOne({searchFor: searchTerm});
我可以通過以下方式獲取格式化日期:
item.formatDate('startDate'); // for startDate field (see exampleSchema), or
item.formatDate('endDate'); // for endDate field (see exampleSchema), or
item.formatDate('whateverDate'); // for whateverDate field (see exampleSchema).
如果物品是從Express傳遞到HTML,例如:
res.render('mypage', {item});
然后它可以在 HTML 中使用(至少對於ejs視圖引擎而言)作為:
<%= item.formatDate('startDate') %>
<%= item.formatDate('endDate') %>
<%= item.formatDate('whateverDate') %>
也許這有點啰嗦,盡管它對我來說效果很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.