我有一個存盤日期的 MongoDB 集合 (SlopeDay)。

在我的快速路由中,我希望將日期格式化為 MM-DD-YYYY,以便我可以將其用于 URL。該 URL 將找到所有具有匹配日期和匹配的檔案resortNames。
dateRouter.get("/:formattedDate", (req, res) => {
const formattedDate = req.params.formattedDate;
SlopeDay.find({}) // isolate dates
.then((dateObj) => {
dateObj.forEach((date, i) => {
let dateStr =
// MM-DD-YYYY reformatting to string
("0" (date.date.getMonth() 1)).slice(-2)
"-"
("0" date.date.getDate()).slice(-2)
"-"
date.date.getFullYear();
// map below doesn't seem to be doing much
const objWithFormattedDate = dateObj.map((obj) => {
return { ...obj, formattedDate: dateStr, isNew: true };
});
// console.log(objWithFormattedDate);
});
});
});
我不知道如何正確地做到這一點。我需要獲取路徑來訪問所有與 MM-DD-YYYY 引數 URL 匹配的日期的 SlopeDay 檔案。
uj5u.com熱心網友回復:
我可以通過分解字串并以這種方式查詢來使其作業:
dateRouter.get("/:formattedDate", (req, res) => {
const formattedDate = req.params.formattedDate;
// break up the date
const targetChars = formattedDate.substring(3, 5);
const beforeTargetChar = formattedDate.substring(0, 3);
const afterTargetChar = formattedDate.substring(5);
// create lower and upper boundaries that straddle the formatted date
const lowerbound = beforeTargetChar (targetChars - 1) afterTargetChar;
const upperbound =
beforeTargetChar (Number(targetChars) 1) afterTargetChar;
SlopeDay.find({
date: {
// find docs with dates between the boundaries (THIS SHOULD EQUAL req.params.formattedDate)
$gte: new Date(lowerbound),
$lt: new Date(upperbound),
}, // add 2nd query here
}).then((dateData) => res.send(dateData));
});
uj5u.com熱心網友回復:
僅使用 Javascript 我可以推薦這篇可能有幫助的帖子
否則,您也可以使用許多庫來執行此操作。我個人喜歡使用 Day.JS。他們的格式功能看起來像這樣,如果你想走那條路,應該滿足你的需求和更多。
dayjs(yourDateHere).format('MM-DD-YYYY')
干杯!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/463099.html
