首页 > 解决方案 > 将技术日期格式化为 MongoDB 中用户可以理解的格式

问题描述

{
  time : "2016-04-30T21" 
}

需要格式化用户可以理解的日期。

预期输出:

{
  time: 21h 30.04.2016
}

标签: mongodbmongoosemongodb-queryaggregation-framework

解决方案


  • $dateFromString to convert date to date type from string
  • $dateToString convert above converted date to specific format
db.collection.aggregate([
  {
    $project: {
      time: {
        "$dateToString": {
          "date": {
            "$dateFromString": {
              "dateString": "$time",
              "format": "%Y-%m-%dT%H"
            }
          },
          "format": "%Hh %d.%m.%Y"
        }
      }
    }
  }
])

Playground

NOTE:

  • It would be easy and fast this conversation in the client-side language (node/js), I would not recommend this date format customization approach in the query because why we add more process time in the query instead we can achieve in client-side in quickly.
  • I would suggest you store this date to date type instead of string type because it will really help to match query and conversation to specific timezone format without any extra operators.

推荐阅读