简体   繁体   English

使用 javascript 从日期到日期验证

[英]From date to date validation using javascript

I want to validate from and to date.我想从和至今进行验证。 my date format is d/m/YH:i我的日期格式是 d/m/YH:i

Here is my code:这是我的代码:

    var startDate = new Date($('#fromdate').val());
    var endDate = new Date($('#todate').val());
    if (endDate.getTime() <= startDate.getTime()) {
        return [false,"To Date cannot be less than From Date"];
    }else{
        return [true,""];
    }

result showing 'Invalid Date'.结果显示“无效日期”。

Here the date format is different.这里的日期格式是不同的。 How to change the date format before passing to Date function?.如何在传递给日期函数之前更改日期格式?。

You can parse the date string on your own or you can use an external library, like dayjs or momentjs您可以自己解析日期字符串,也可以使用外部库,如dayjsmomentjs

A simple parsing function could be something like this (assuming the format is the one you mentioned in your question):一个简单的解析函数可能是这样的(假设格式是您在问题中提到的格式):

function getDateFromCustomFormat(dateString) {
  const dateFormatPattern = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2})$/

  const parts = dateString.match(dateFormatPattern)
  console.log(parts)

  const validFormatString = `${parts[3]}-${parts[2]}-${parts[1]} ${parts[4]}:${parts[5]}`
  new Date(validFormatString)
}

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

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