Reputation: 361
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
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
Reputation: 348992
There's no need to use the Date
object for this case. Simple math is sufficient:
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
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
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