【问题标题】:Mongodb - convert the datetime to ISOdate formatMongodb - 将日期时间转换为 ISOdate 格式
【发布时间】:2018-02-22 17:08:12
【问题描述】:

我想将现有字符串日期转换为新的 ISO 日期格式。我使用了一些脚本,但它们不足以将时间转换为日期。例如:2013-01-10 12:22:22 AM 转换为 ISODate("2013-01-10T06:00:00Z")。这里时间没有转换。请帮忙。

var cursor = db.customer.find({"created_at": {"$exists": true, "$type": 2 }}); 
while (cursor.hasNext()) { 
      var doc = cursor.next(); 
      var parts = doc.created_at.split("-");
      var dt = new Date(
            parseInt(parts[0], 10), // year
            parseInt(parts[1], 10) - 1, // month
            parseInt(parts[2], 10)// day

        );
   db.customer.update(
    {"_id": doc._id}, 
    {"$set": {"created_at": dt}}
   ) 
}

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    只需使用 new ISODate() :

    new ISODate("2013-01-10 12:22:22 AM ")
    ISODate("2013-01-10T12:22:22Z")
    

    在您的完整示例中:

    var cursor = db.customer.find({"created_at": {"$exists": true, "$type": 2 }}); 
    while (cursor.hasNext()) { 
       var doc = cursor.next(); 
       db.customer.update(
        {"_id": doc._id}, 
        {"$set": {"created_at": new ISODate(doc.created_at)}}
       ) 
    }
    

    【讨论】:

    • 谢谢,上面我可以用分隔符 - 更新日期。我无法更新像“2013/01/10 12:22:22 AM”这样的日期。请指教
    • 您也可以在您的 mongodb 请求中使用 js Date 类型(它将被转换为 ISODate)。 new Date("2013/01/10 12:22:22 AM") 将起作用。
    • new Date 转换日期,但它会转到默认日期 1970-01-01:00:00:00。并没有真正帮助我。
    • 我收到错误,ISODate 没有定义!我需要下载一些东西吗?
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2019-06-15
    • 1970-01-01
    • 2015-05-21
    • 2017-12-09
    • 2015-03-23
    相关资源
    最近更新 更多