0

I want to validate from and to date. my date format is d/m/Y H: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?.

ManUtd
  • 23
  • 1
  • 8
  • next time please add example input. – Amnon Mar 15 '20 at 11:19
  • However, you can parse the given date using [Date.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) – Amnon Mar 15 '20 at 11:19
  • See [What are valid Date Time Strings in JavaScript?](https://stackoverflow.com/questions/51715259/what-are-valid-date-time-strings-in-javascript/) – str Mar 16 '20 at 12:21

1 Answers1

0

You can parse the date string on your own or you can use an external library, like dayjs or momentjs

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)
}

ulentini
  • 2,413
  • 1
  • 14
  • 26
  • I believe OP knows that the format is incorrect and is asking **how** it can be changed – Anurag Srivastava Mar 15 '20 at 09:18
  • @AnuragSrivastava you're right, I'm gonna change my answer. – ulentini Mar 15 '20 at 09:20
  • Parsing a string to create another string that is then parsed by the built–in parser is not a good strategy. From the initial parse, pass the values directly the Date constructor. Dates in the format y-m-d h:m are not supported by ECMA-262 so parsing is implementation dependent and at least one current implementation will return an invalid date. – RobG Mar 15 '20 at 21:48