简体   繁体   中英

How to create UTC Time in Express for Mongo Query in Express.js

This has probably been asked a hundred times, yet I dare to ask: In express / mongoose I need to create a UTC ISO date in order to query MongoDB. This is what I am doing:

var date = new Date(req.params.date + " 00:00:00 UTC").toUTCString();

Whereas req.params.date equals this string: 2015-01-01 .

Above line creates: Mon, 12 Jan 2015 00:00:00 GMT , in MongoDB I have:

"date" : ISODate("2014-12-08T00:00:00.000Z")

How do I get this to work?

You need to represent the date in your query as a standard JavaScript Date object.

So leave off the toUTCString() part and something like this will work:

var date = new Date(req.params.date);
collection.findOne({date: date}, callback);

The ISODate stuff confuses so many people (myself included for the longest time). ISODate is just a MongoDB shell construct, date objects are stored as 64-bit integer BSON Date objects in MongoDB.

Instead of toUTCString() I used the toISOString() method of the Date object, this worked fine.

var date = new Date(req.params.date + " 00:00:00 UTC").toISOString();

Also see. Inserting and Querying Date with MongoDB and Nodejs

将UTC字符串转换为Date对象

    var utc_date=new Date(new Date().toUTCString());    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM