[英]How to convert date format in nodejs using mongoose
I have a document like this我有一个这样的文件
{
"_id": "5c2326cb5d558f6693577119",
"date": "08/02/16 00:00",
"symbol": "WLTW",
"open": "113.300003",
"close": 111.160004,
"low": 110.459999,
"high": 113.300003,
"volume": 1200500,
"createdAt": "2018-12-26T06:59:23.901Z",
"updatedAt": "2018-12-26T06:59:23.901Z"
}
I am doing a query something like this我正在做这样的查询
const getStockBySymbol = (data) => {
console.log('Hitting Stock Model fine!!')
return Stock.find({symbol: data})
.then((stocks) => {
console.log(stocks)
if (stocks) { return stocks }
})
}
I need to convert the date
format to Year-month-date
format我需要将
date
格式转换为date
Year-month-date
格式
So current format is dd\\mm\\yy
in date
property I want to convert that to yyyy-mm-dd
所以当前格式是
date
属性中的dd\\mm\\yy
我想将其转换为yyyy-mm-dd
I am new with MongoDB would be great if anyone could help如果有人可以提供帮助,我是 MongoDB 的新手会很棒
Thanks谢谢
you need to map results after fetching your data :您需要在获取数据后映射结果:
const getStockBySymbol = (data) => {
return Stock.find({symbol: data})
.then((stocks) => {
if (stocks) {
var newStocks=stocks.map(function(stock){
let formattedDate=moment(stock.date,"dd/mm/YY hh:mm").format("YYYY-mm-dd");
stock.date=formattedDate;
return stock;
});
return newStocks;
}
})
}
You're best option here would be to use momentjs library.您最好的选择是使用 momentjs 库。 It's a no-brainer solution for time format conversion :
这是时间格式转换的简单解决方案:
moment(new Date(date)).format('YYYY-MM-DD');
This should yield '2016-08-02'.这应该产生'2016-08-02'。
You can parse string to ISODate using $dateFromString operator.您可以使用$dateFromString运算符将字符串解析为 ISODate 。 The problem is that all formats for year expect four digits so it will parse your year to
0016
instead of expected 2016
.问题是年份的所有格式都需要四位数,因此它会将您的年份解析为
0016
而不是预期的2016
。 To fix that you can use $dateToParts and $dateFromParts and manually add 2000
.要解决此问题,您可以使用$dateToParts和$dateFromParts并手动添加
2000
。 Then you can use $dateToString to convert it to your format, try:然后您可以使用$dateToString将其转换为您的格式,请尝试:
Stockdb.aggregate([
{
$match: { symbol: "WLTW" }
},
{
$addFields: {
date: {
$dateToParts: {
date: { $dateFromString: { dateString: "$date", format: "%d/%m/%Y %H:%M" } }
}
}
}
},
{
$addFields: {
date: {
$dateToString: {
date: {
$dateFromParts: {
day: "$date.day",
month: "$date.month",
year: { $add: [ 2000, "$date.year" ] }
}
},
format: "%Y-%m-%d"
}
}
}
}
])
$addFields overwrites existing fields in this case $addFields在这种情况下覆盖现有字段
EDIT: for lower MongoDB versions you can use $substr and $concat operators assuming your date
has fixed length:编辑:对于较低的 MongoDB 版本,假设您的
date
具有固定长度,您可以使用$substr和$concat运算符:
Stockdb.aggregate([
{
$match: { symbol: "WLTW" }
},
{
$addFields: {
date: {
$concat: [
'20',
{ $substr: [ "$date", 6, 2 ] },
'-',
{ $substr: [ "$date", 3, 2 ] },
'-',
{ $substr: [ "$date", 0, 2 ] },
]
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.