Newbie007
Newbie007

Reputation: 169

JavaScript new Date() comparison

Here my code,

var date1 = joiningDate.split('-');
  var tempjoiningDate = date1[1] + '-' + date1[0] + '-' + date1[2];
  var date2 = birthdayDate.split('-');
  var tempbirthdayDate = date2[1] + '-' + date2[0] + '-' + date2[2];
  var jd = new Date(date1[0], date1[1] - 1, date1[2]);
  var bd = new Date(date2[0], date2[1] - 1, date2[2]);
  if (jd <= bd) {
  console.log("correct dates");
  }
  else {
  console.log("Incorrect dates");
  }

In this joining date and birthdayDate are in d-m-y format. So i changed to y-m-d format using split and compare these two dates. But it is not working as i expected.

Is anything wrong in this?

Upvotes: 1

Views: 63

Answers (2)

gurvinder372
gurvinder372

Reputation: 68393

Set the time part to 0

jd.setHours( 0, 0, 0, 0 );
bd.setHours( 0, 0, 0, 0 );

Change the condition to

if (jd.getTime() <= bd.getTime()) {

Edit

Original comparison should work as is

if (jd <= bd) {

Demo

var joiningDate = "05-02-2018";
var birthDate = "08-01-2016";

var fnToDate = str => { 
  var items = str.split( "-" );
  var date = new Date( items[2], items[1] - 1, items[0] );
  date.setHours( 0, 0, 0, 0 );
  return date;
};

console.log( fnToDate( joiningDate ) );
console.log( fnToDate( birthDate ) );
console.log( fnToDate( joiningDate ) < fnToDate( birthDate ) );

Upvotes: 0

ESP32
ESP32

Reputation: 8728

Your script nearly works. Date() expects the parameters as Integers. So you should cast the strings with leading zeros, using parseInt.

Further more: Are you sure, that Joindate should be earlier than Birthdate??

var joiningDate = '2018-03-08';
var birthdayDate = '1960-01-01';

  var date1 = joiningDate.split('-');
  var date2 = birthdayDate.split('-');
  var jd = new Date(parseInt(date1[0]), parseInt(date1[1]) - 1, parseInt(date1[2]));
  var bd = new Date(parseInt(date2[0]), parseInt(date2[1]) - 1, parseInt(date2[2]));
 
  if (jd <= bd) {
    console.log("Join Date is earlier");
  }
  else {
    console.log("Birth Date is earlier");
  }
  

But you could also directly pass the date strings to the Date object:

var jd = new Date(joiningDate); 

See here for an explanation of the Date Object:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Upvotes: 1

Related Questions