0

I have a date-picker on my web application that produces the following output 25-04-2018 16:50:

enter image description here

It is: day-month-year hour:minute.

The idea is that I'll have two input-text, and the first date has to be before the second date. Otherwise, swap the dates.

I want to compare two dates in this format, so I try to create a Date object:

<input onchange="date()" type="text" readonly id="datetimepicker_1"/>
<input onchange="date()" type="text" readonly id="datetimepicker_2"/>

<script>
    function date() {
        var start = document.getElementById("datetimepicker_1");
        var end = document.getElementById("datetimepicker_2");
        if (start.value.trim() && end.value.trim()) {
            var dateStart = new Date(start.value);
            var dateEnd = new Date(end.value);

            if (dateStart > dateEnd){
                document.getElementById("datetimepicker_1").value = end.value;
                document.getElementById("datetimepicker_2").value = start.value;
            }    
        }
</script>

But I have the following error: Invalid Date. How I can compare these dates?

Lechucico
  • 1,914
  • 7
  • 27
  • 60
  • 4
    The `Date.parse()` function only tolerates the date formats it wants to, and that's not even consistent between browsers. You can write your own code to interpret your format and make Date instances with the various numeric Date APIs, or you can use a library like moment.js. – Pointy Apr 25 '18 at 14:59
  • 2
    consider using a library like https://momentjs.com so you can do `var date = moment(start.value,'DD-MM-YYYY HH:mm');` – Tschallacka Apr 25 '18 at 15:02
  • Use an `input type='date'` that takes care of a lot of this for you - including the behavior of valid and invalid input. – Benjamin Gruenbaum Apr 25 '18 at 15:04

1 Answers1

1

It looks like JavaScript isn't tolerating the format of your date.

You have the date in format of "Day-Month-Year Hour-Minute" Or DD-MM-YYYY

I was able to get the following code to work in two scenarios; having the date in the format : "Year-Month-Day Hour-Minute" or "Month-Day-Year Hour Minute"

This code is very poorly written but I think it illustrates the idea.

function DatePicker()
{
var datestart = new Date("2018-04-25 16:50"); //or 04-25-2018 16:50
console.log(datestart);
var datestart2 = new Date("2018-04-25 16:55"); //or 04-25-2018 16:50
console.log(datestart2);

if (datestart < datestart2)
{
    console.log("success");
} else {
    console.log("failed");
}

}

DatePicker();

I recognize that different countries in the world use different date formats. So to solve your issue I would recommend using "Moment.js" so you are able to format the date to your liking or needs as laid out in the Stack Overflow question and answer linked below.

DD/MM/YYYY Date format in Moment.js

Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35
Casper-Evil
  • 31
  • 1
  • 2