简体   繁体   English

如何比较时刻js中的日期时间

[英]How to Compare Date time in moment js

Hi I need to validate two date time moment instances, Using this Package to get time we can select hour min sec in this.您好我需要验证两个日期时间时刻实例,使用这个Package来获取时间我们可以 select 小时分钟秒。 I need validate if selected Date time is after or before like you see in code.I'm having confusion will it validate date with time?我需要验证所选日期时间是否像您在代码中看到的那样晚于或早于。我很困惑它会随时间验证日期吗? How to compare selected date time hour min sec in isAfter/isBefore如何在 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
      }

should i need to format selected date needed format -(dd/mm/yyyy hh:mm:ss) and then apply isBefore/isafter?我是否需要格式化所选日期所需的格式 -(dd/mm/yyyy hh:mm:ss) 然后应用 isBefore/isafter? Please help...请帮忙...

Yes it will validate date along with the time.是的,它将与时间一起验证日期。 Here is the code which shows the 1 second difference between two dates.这是显示两个日期之间相差 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)

To see it in action take a look here .要查看实际效果,请点击此处

It looks like, in your example, the selectedDate is not a valid moment object. selectedDate needs to be a valid moment object in order to successfully apply the isAfter() and isBefore() methods, and startTime and endTime must also be in the correct format.看起来,在您的示例中,selectedDate 不是有效时刻 object。selectedDate 需要是有效时刻 object 才能成功应用 isAfter() 和 isBefore() 方法,并且 startTime 和 endTime 也必须在正确的位置格式。 See the examples in the docs: https://momentjs.com/docs/#/query/is-after/ .请参阅文档中的示例: https://momentjs.com/docs/#/query/is-after/

If you know the format ahead of time, you can pass that as the second argument into moment().如果您提前知道格式,则可以将其作为第二个参数传递给 moment()。 See the relevant part of the docs: momentjs.com/docs/#/parsing/string-format.请参阅文档的相关部分:momentjs.com/docs/#/parsing/string-format。 In your example, something like moment("10/09/1997 02:31:01", "dd/mm/yyyy hh:mm:ss")在您的示例中,类似于moment("10/09/1997 02:31:01", "dd/mm/yyyy hh:mm:ss")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM