【问题标题】:How to separate month and year in Date in pug如何在哈巴狗的日期中分隔月份和年份
【发布时间】:2022-01-26 17:37:10
【问题描述】:

这是保存在 MongoDB 中的日期格式:

Sun Feb 13 2022 05:30:00 GMT+0530 (India Standard Time)

如何在 pug 中将月、年和日与这个日期分开?我想在哈巴狗中取这个日期并分别显示月份和年份。

【问题讨论】:

  • 日期值应该从不存储为字符串,始终存储正确的Date 对象。在 MongoDB 中本地解析此类字符串非常困难。我建议第三方库,最常见的是moment.jsluxonday.js
  • 这看起来更像是 Compass 等工具显示的日期格式。数据库中该字段的$type 是什么?

标签: node.js mongodb express mongoose pug


【解决方案1】:

Pug 是基于 JavaScript 构建的,因此您可以只使用字符串操作来解析月、日和年——假设格式是一致的。

-
  // variable containing date string
  const myString = "Sun Feb 13 2022 05:30:00 GMT+0530 (India Standard Time)"
  // break into individual variables using destructuring
  let [dayOfWeek, month, day, year, time, timeZone, timeZoneName] = myString.split(' ')

p.postDate Posted on #{month} #{day}, #{year}

【讨论】:

    【解决方案2】:

    感谢大家的帮助,我找到了一个名为 moment.js 的 npm 库。它非常易于使用,并且具有许多内置功能。

    【讨论】:

      猜你喜欢
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多