1

There are two date fields namely 'Date 1' and 'Date 2'. On clicking the button 'Check', the maximum of the two dates need to be printed in the 'Max Date' field. So how to print the max date from a set of dates. I have tried pushing the date values into an array and finding out the max, but something seems wrong. Below is the HTML and javascript code.

function checkMaxDate() {
    var dateArray = [];
    var date1 = dateArray.push(document.getElementById('date1').value);
    var date2 = dateArray.push(document.getElementById('date2').value);
    var maxDate = Math.max.apply(Math, dateArray);
    document.getElementById('maxdate').value = maxDate;
}
Date 1: <input type="date" id="date1" />
Date 2: <input type="date" id="date2" />
Max Date: <input type="date" id="maxdate" />
<button type="button" onclick="checkMaxDate()">Check</button>

2
  • 1
    Your values will be strings, not dates. Does the user enter the dates themself? If so how do you know which format they will use? Commented Oct 21, 2015 at 15:32
  • Yes the user would enter the dates. The format is dd-mm-yyyy Commented Oct 21, 2015 at 16:52

2 Answers 2

2

Try wrapping document.getElementById('date1').value in new Date().getTime() .

Also input type="date" accepts value as yyyy-mm-dd ; try using .toJSON() , String.prototype.slice() to set date properly for #maxdate as yyyy-mm-dd from value returned as maxDate

function checkMaxDate() {
  var dateArray = [];
  var date1 = dateArray.push(new Date(document.getElementById('date1').value).getTime());
  var date2 = dateArray.push(new Date(document.getElementById('date2').value).getTime());
  var maxDate = Math.max.apply(Math, dateArray);
  document.getElementById('maxdate').value = new Date(maxDate).toJSON().slice(0, 10);
}
Date 1:
<input type="date" id="date1" />Date 2:
<input type="date" id="date2" />Max Date:
<input type="date" id="maxdate" />
<button type="button" onclick="checkMaxDate()">Check</button>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. This helped a lot and it worked.
2

You were close. Try applying the function inside a newDate, and null instead of Math. You should also new Date(pushedArrayElement) to be a Date object, and not push Strings into the date array.

var maxDate= new Date(Math.max.apply(null,dateArray));

Note that there's cause for error because it's not guaranteed that the user input will be a legal date format.

3 Comments

What about the fact that the 2 inputs are strings, not dates?
@SterlingArcher input type="date" accepts setting date as yyyy-mm-dd , not as value of new Date()
Thank you very much, this helped a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.