Gryz Oshea
Gryz Oshea

Reputation: 361

Compare years and month with jQuery

var onemonth = 3;
var oneyear = 2005;
var twomonth = 10;
var twoyear = 2000;

How can i split this and compare? In this example is:

var firstdate = onemonth + oneyear;
var seconddate = twomonth + twoyear;

if(firstdate < seconddate){
 alert('error');
}

How is the best method for compare two date if i have only month and year?

LIVE: http://jsfiddle.net/26zms/

Upvotes: 2

Views: 5737

Answers (4)

Petr Vostrel
Petr Vostrel

Reputation: 2332

What about using the native Date object like this?

if (new Date(oneyear, onemonth) < new Date(twoyear, twomonth)){
  alert('error');
}else{
  alert('ok');
}

With your variables it will yield "ok".

Upvotes: 4

Rob W
Rob W

Reputation: 348992

There's no need to use the Date object for this case. Simple math is sufficient:

  • Divide the month by twelve.
  • Add this value to the year.
  • Do the same for the other date(s), and compare the values:

Code:

var onemonth = 3;
var oneyear = 2005;
var twomonth = 10;
var twoyear = 2000;

var year1 = oneyear + onemonth / 12;
var year2 = twoyear + twomonth / 12;
if (year1 < year2) {
    // error?
}

Upvotes: 1

Pranay Rana
Pranay Rana

Reputation: 176896

acording to me append zero and than concate string

var onemonth = 3; 
if(onemonth < 10)
 onemonth = "0" + onemonth;
var oneyear = 2005; 
var oneyearmonth = oneyear + onemonth; // 200503
var twomonth = 10; 
if(twomonth < 10)
 twomonth = "0" + twomonth ;
var twoyear = 2000;
var twoyearmonth = twoyear + twomonth ; //200010
if(oneyearmonth < twoyearmonth)
{
   alert("one month and year leass than tow month and year");
}

Upvotes: 1

Alex K.
Alex K.

Reputation: 175766

Make then proper dates;

var firstdate =  new Date(oneyear, onemonth - 1, 1); 
var seconddate = new Date(twoyear, twomonth - 1, 1); 

Then the comparison is valid (as opposed to comparing arbitrarily created integers)

Upvotes: 2

Related Questions