【问题标题】:Is there any way to display time format with am/pm in mongodb有没有办法在mongodb中用am/pm显示时间格式
【发布时间】:2022-02-17 10:42:53
【问题描述】:

时间: { $dateToString: { format: "%H:%M:%S:%L%z", date: "$generated_on", timezone: "+05:30" }} 在这个时间的帮助下生成,但我想要 AM/PM 格式的时间}\

【问题讨论】:

  • 如果你在管道中使用它,我猜你需要添加一个自定义 js 函数,但我认为更好的选择是首先存储正确的格式

标签: node.js mongodb


【解决方案1】:

所以基本上,暂时(版本 5)Mongo DB does not support 日期对象的 AM/PM 格式,您有两个选择:

选项一:首先存储正确的格式

选项二(繁重的操作):在 MongoDB 中存储一个 JS 函数,用于这种自定义格式,并在您的聚合管道中调用它,js function would be like this

   function formatAMPM(date) {
      var hours = date.getHours();
      var minutes = date.getMinutes();
      var ampm = hours >= 12 ? 'PM' : 'AM';
      hours = hours % 12;
      hours = hours ? hours : 12; // the hour '0' should be '12'
      minutes = minutes < 10 ? '0'+minutes : minutes;
      var strTime = hours + ':' + minutes + ' ' + ampm;
      return strTime;
    }

添加MongoDB自定义JS函数myCustomDate

 db.system.js.insertOne(
    {
        _id: "myCustomDate",
        value: function (date) {
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var ampm = hours >= 12 ? 'PM' : 'AM';
            hours = hours % 12;
            hours = hours ? hours : 12; // the hour '0' should be '12'
            minutes = minutes < 10 ? '0' + minutes : minutes;
            var strTime = hours + ':' + minutes + ' ' + ampm;
            return strTime;
        }
    }
);

并根据您的要求使用它on mapReduce command

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-19
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    相关资源
    最近更新 更多