【问题标题】:How to Compare Date time in moment js如何比较时刻js中的日期时间
【发布时间】:2020-12-10 12:26:34
【问题描述】:

您好,我需要验证两个日期时间时刻实例, 使用这个Package 来获取时间,我们可以在其中选择小时分钟秒。 我需要验证选择的日期时间是否在您在代码中看到的之后或之前。我很困惑它会用时间验证日期吗? 如何在 isAfter/isBefore 中比较选定的日期时间小时分钟秒

 function DateValidate(selectedDate,type){ //selected date in moment instance
      let isValid=false
      const {startTime,endTime}=dateTime // from state 
       if(type==='start'&& endTime){
            isValid=selectedDate.isAfter(endTime);
          }else if(type==='end'&& startTime){
          isValid=selectedDate.isBefore(startTime);
          }
       return isValid
      }

我是否需要格式化所选日期所需的格式 -(dd/mm/yyyy hh:mm:ss) 然后应用 isBefore/isafter ? 请帮忙...

【问题讨论】:

  • 你能分享一些示例输入和输出吗?
  • 嗨@HassanImam 我需要知道这个实现将验证时间,或者我需要在 dd/mm/yyyy hh:mm:ss 中格式化当前日期然后验证
  • 为什么函数中有两个selectedDate?一个在争论中,另一个在第 3 行。
  • 对不起我的错误我已经更新了问题
  • @Dev,如果你有一个有效的时刻对象,那么它也会验证时间(你不需要格式化日期)。

标签: javascript reactjs momentjs


【解决方案1】:

看起来,在您的示例中, selectedDate 不是有效的时刻对象。 selectedDate 必须是有效的 moment 对象才能成功应用 isAfter() 和 isBefore() 方法,并且 startTime 和 endTime 也必须采用正确的格式。请参阅文档中的示例:https://momentjs.com/docs/#/query/is-after/

如果您提前知道格式,则可以将其作为第二个参数传递给 moment()。请参阅文档的相关部分:momentjs.com/docs/#/parsing/string-format。在您的示例中,类似于moment("10/09/1997 02:31:01", "dd/mm/yyyy hh:mm:ss")

【讨论】:

  • 是@Omid 使用的所有日期都是时刻对象。如何格式化应用的所选日期 isAfter /isBefore 。我应该像这样格式化 dd/mm/yyyy hh:mm:ss 我该怎么做这样做
  • 如果您提前知道格式,您可以将其作为第二个参数传递给 moment()。请参阅文档的相关部分:momentjs.com/docs/#/parsing/string-format。在您的示例中,类似于moment("10/09/1997 02:31:01", "dd/mm/yyyy hh:mm:ss")
【解决方案2】:

是的,它将验证日期和时间。这是显示两个日期之间相差 1 秒的代码。

const out = document.getElementById('output');

const today = moment();
var afterToday;
setTimeout(()=>{
    afterToday = moment();
}, 1000)

setTimeout(()=>{

    //const diff = afterToday.isAfter(today);
  const diff = today.isAfter(afterToday);
  out.innerText = diff;
}, 2000)

要查看它的实际效果,请查看here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-21
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 2012-01-20
    相关资源
    最近更新 更多