用jQuery比较年月和月份

时间:2012-02-21 15:20:18

标签: javascript jquery

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

我如何拆分并比较? 在这个例子中是:

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

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

如果我只有月份和年份,那么比较两个日期的最佳方法是什么?

现场:http://jsfiddle.net/26zms/

4 个答案:

答案 0 :(得分:4)

如何使用像这样的原生Date对象?

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

使用你的变量它会产生“ok”。

答案 1 :(得分:2)

制作适当的日期;

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

然后比较有效(而不是比较任意创建的整数)

答案 2 :(得分:1)

根据我追加零然后连接字符串

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");
}

答案 3 :(得分:1)

在这种情况下,无需使用Date对象。简单的数学就足够了:

  • 将月份除以十二。
  • 将此值添加到年份。
  • 对其他日期执行相同操作,并比较值:

代码:

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?
}