-3

this was mine third school assignment

Write a JavaScript function that compares two dates. Call this function compare_date () and give this function two input parameters. Take off the code below and make sure the window.alert () returns a message or date one is greater or less than 2 date or perhaps date 1 equals 2 date

i got something like this

var d1 = new Date(2017, 0, 2); // 2 januari 2017 
var d2 = new Date(2017, 0, 1); // 1 januari 2017

window.alert(compare_date(d1,d2));


function compare_date(date1,date2){  


}  
almcd
  • 1,069
  • 2
  • 16
  • 29
Dimitri
  • 69
  • 1
  • 7

4 Answers4

1

Here you go:

var d1 = new Date(2017, 0, 2); // 2 januari 2017 
var d2 = new Date(2017, 0, 1); // 1 januari 2017

compare_date(d1,d2);
    
function compare_date(date1,date2){  
   if (date1 > date2) {
        alert("Date One is greather than Date Two.");
   }else if (date2 > date1) {
        alert("Date Two is greather than Date One.");
   }else{
       alert("Both are equal.");
   }
}

JSFiddle Demo

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
0

You can try the below one which is just a simple one like date1 > date2.

Note: date1 > date2 and date1.getTime() > date2.getTime() are same.

var d1 = new Date(2017, 0, 2); // 2 januari 2017 
var d2 = new Date(2017, 0, 1); // 1 januari 2017

window.alert(compare_date(d1,d2));


function compare_date(date1, date2){  
 return (date1.getTime() === date2.getTime() ? 'Equal' : (date1 > date2 ? 'date1 is greater than date 2' : 'date1 is less than date2'));

}  
Aruna
  • 11,959
  • 3
  • 28
  • 42
0

something like this?

var d1 = new Date(2017, 0, 2); // 2 januari 2017 
var d2 = new Date(2017, 0, 1); // 1 januari 2017

window.alert(compare_date(d1,d2));


function compare_date(date1,date2){  
  var diff = date1 - date2;
 if (diff < 0)
   return "date 2 is bigger";
  else
  if (diff > 0)
   return "date 1 is bigger";
  else
  return "are the same"

}  
Jordi Flores
  • 2,080
  • 10
  • 16
0

EDIT : Math.sign() is Ecmascript 2015

make a reusable function:

return 0 if dates are equal

return -1 if d1 is before d2

return 1 if d1 is after d2

var d1 = new Date(2017, 0, 2); // 2 januari 2017
var d2 = new Date(2017, 0, 1); // 1 januari 2017

window.alert(compare_date(d1,d2));


function compare_date(date1, date2){  
    return Math.sign(date1.getTime() - date2.getTime());
}
techws
  • 108
  • 8