使用Moment JS在JavaScript中将日期转换为MongoDB ISODate格式
MongoDB使用ISODate作为其主要日期类型。如果您想将日期对象插入MongoDB集合中,可以使用 Date() shell方法。
您可以通过向 new Date() 构造函数或 ISODate() 函数传递包含年份的 ISO-8601 日期字符串来指定特定日期。这些函数接受以下格式:
- new Date(
"<YYYY-mm-dd>"
) 返回指定日期的 ISODate。
- new Date(
"<YYYY-mm-ddTHH:MM:ss>"
) 指定客户端本地时区的日期时间,并返回具有指定 UTC 日期时间的 ISODate。
- new Date(
"<YYYY-mm-ddTHH:MM:ssZ>"
) 指定 UTC 的日期时间,并返回具有指定 UTC 日期时间的 ISODate。
- new Date() 将日期时间指定为 Unix 纪元(1970 年 1 月 1 日)以来的毫秒数,并返回生成的 ISODate 实例。
如果您正在使用 JavaScript 编写代码并希望传递 JavaScript 日期对象并与 MongoDB 客户端一起使用,则首先要做的是将 JavaScript 日期转换为 MongoDB 日期格式(ISODate)。以下是如何操作。
var today = moment(new Date()).format('YYYY-MM-DD[T00:00:00.000Z]');
console.log("Next day -- " + (reqDate.getDate() + 1))
var d = new Date();
d.setDate(reqDate.getDate() + 1);
var tomorrow = moment(d).format('YYYY-MM-DD[T00:00:00.000Z]');
使用新的Date() shell方法,您可以将今天和明天的对象传递给MongoDB查询。
MongoClient.connect(con, function (err, db) {
if (err) throw err
db.collection('orders').find({ "order_id": store_id, "orderDate": {
"$gte": new Date(today), "$lt": new Date(tomorrow)}
}).toArray(function (err, result) {
console.log(result);
if (err) throw err
res.send(result);
})
})