【问题标题】:Format of date to compare two dates, one coming from mogo database, the other from one http request比较两个日期的日期格式,一个来自 mogo 数据库,另一个来自一个 http 请求
【发布时间】:2019-05-28 22:58:23
【问题描述】:

我想比较日期以在 express 函数中执行一些逻辑。 来自 mongodb 并在 mongoose 模式中使用 Date 对象定义的一个日期具有以下格式:

date: "1991-12-12T00:00:00.000Z"

来自 http 请求的另一个日期是格式为 YYYY-MM-DD 的字符串

 http://www.web.com/path1/path2?from=1990-12-31&to=2000-12-31

如何在回调函数中实现两个日期比较来实现一些逻辑

 if ( "1991-12-12T00:00:00.000Z" > from &&  "1991-12-12T00:00:00.000Z" < to){
           ...some logic here
 }

【问题讨论】:

  • 使用 moment.js 获得准确的结果和比较

标签: node.js mongodb express mongoose mongodb-query


【解决方案1】:

使用Moment.js 确定这些日期是否在同一天内。 Moment.js 还包括诸如“isBefore”、“isAfter”、“isSameOrBefore”、“isSameOrAfter”之类的方法,您可能希望使用这些方法来实现您的目标。

const isSameDay = moment('1991-12-12T00:00:00.000Z', 'YYYY-MM-DDTHH:mm:ss.SSSZ')
    .isSame(moment('1991-12-12','YYYY-MM-DD'), 'day');
if(isSameDay) {
  console.log('Dates are within the same day');
} else {
  console.log('Dates are not within the same day');
}
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 是的,就是这样。我已经看过了,但我不知道这些方法。我错误地尝试了比较运算符(>、
  • @user1881983 如果有帮助请标记为答案
猜你喜欢
  • 2012-01-31
  • 2021-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多