如何将日期字符串如“17-DEC-1980”转换为MongoDB的日期格式?

时间:2013-02-05 16:26:27

标签: mongodb date

我有一些数据和17-DEC-1980这样的格式。如何将其转换为Date对象并插入MongoDB?

感谢。

1 个答案:

答案 0 :(得分:4)

Javascript控制台(此代码取决于时区):

d = Date.parse('17-DEC-1980'); // 345844800000

然后将此值输入mongodb请求:

> new Date(345844800000)
ISODate("1980-12-16T20:00:00Z") // copy from MongoDB shell 

Node.js(example.js):

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});

    var mongodb = require('mongodb');
    var server = new mongodb.Server("127.0.0.1", 27017, {});
    new mongodb.Db('se', server, {}).open(function (error, client) {
      if (error) throw error;
      var collection = new mongodb.Collection(client, 'test_collection');

      d = Date.parse('17-DEC-1980');
      collection.insert({dt: new Date(d)}, {safe:true}, function(err, objects) {
        if (err) console.warn(err.message);
        if (err && err.message.indexOf('E11000 ') !== -1) {
          // this _id was already inserted in the database
        }
      });
    });

  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');