Check the difference between two dates with a custom JavaScript implementation

This might be useful if you are having problems with different browsers and how they handle JavaScript and date + time data.


var duedateString = "you due date time value here";

 var today = new Date();

 var ddYear = parseInt(duedateString.substring(0 ,4));
 var ddMonth = parseInt(duedateString.substring(4 ,6));
 var ddDay = parseInt(duedateString.substring(6 ,8));

 var yearDifference = ddYear - (today.getFullYear()) ;
 var monthDifference = ddMonth - (today.getMonth() +1);
 var dayDifference = ddDay - (today.getDate());
 var stringDueDateParsed = duedateString.substring(6 ,8) + "." + duedateString.substring(4 ,6) + "." + duedateString.substring(0 ,4);
 var dueDate = new Date((ddYear),(ddMonth),(ddDay));

 var totalDifference = 0;

 if(yearDifference < 0)
 {
 totalDifference = -1;
 } else if(yearDifference > 0)
 {
 totalDifference = 1;
 } else if(monthDifference < 0)
 {
 totalDifference = -1;
 } else if(monthDifference > 0)
 {
 totalDifference = 1;
 } else if(dayDifference < 0)
 {
 totalDifference = -1;
 } else if(dayDifference > 0)
 {
 totalDifference = 1;
 } else
 {
 totalDifference = 0;
 }

 // the dates are equal
 if(totalDifference === 0)
 {
 // do something
 }
 // The dueDate is greater than the current date, in the future
 else if(totalDifference > 0)
 {
 // do something
 }
 // The dueDate is smaller than the current date, in the past
 else if(totalDifference < 0)
 {
 // do something
 }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s