2011-10-19 47 views
0
var monthDiff = today.getMonth() - pastdate.getMonth(); 
var hadBirthdayThisMonth = 
    (today.getMonth() > pastdate.getMonth()) ? 
     true : (today.getMonth() < pastdate.getMonth()) ? 
      false : (today.getDate() > pastdate.getDate()) ? 
       true : (today.getDate() < pastdate.getDate()) ? false : true; 
if (!hadBirthdayThisMonth) monthDiff--; 

8月20 2011年至2011年9月19日,天數是60,它顯示了2個月爲我,但我想說明它one個月到他生日的Sept 20th來。他這個月有沒有生日?

我想出了上述邏輯,但它不起作用。

+2

神聖的嵌套三元運算符,蝙蝠俠! O_O – deceze

+0

另外,問題是什麼?你只是想知道直到下一個生日有多少個月?或者僅僅是這個月的生日是不是? – deceze

+2

*「我想出了上述邏輯,但它不起作用。」* - 我想知道爲什麼;) –

回答

1
function isBDayInMonth(month, day) { 
    var today = new Date(), 
     birthDay = new Date(today.getFullYear(), month - 1, day, 0, 0, 0, 0); /*compose date*/ 

    return (birthDay.getMonth() - today.getMonth() === 0) ? { 
     "msg": "this month", 
     "days": parseInt((birthDay.getTime() - today.getTime())/864E5, 10) === 0 ? "tomorrow" : parseInt((birthDay.getTime() - today.getTime())/864E5, 10) + " days remaining" 
    } : (birthDay.getMonth() - today.getMonth() === 1) ? { 
     "msg": "next month", 
     "days": parseInt((birthDay.getTime() - today.getTime())/864E5, 10) + " days remaining" 
    } : (today.getMonth() > birthDay.getMonth()) ? { 
     "msg": "in " + ((11 - today.getMonth()) + birthDay.getMonth()) + " months", 
     "days": "many days remaining" 
    } : { 
     "msg": "in " + (birthDay.getMonth() - today.getMonth()) + " months", 
     "days": "many days remaining" 
    }; 
} 

作品在所有情況下 - 只返回一個對象,具有2個道具:

  • 約一個月資訊
  • 關於天
  • 信息,數字顯示只有當生日是在下個月

Demo

1

從8月20日2011年至2011年9月19日,天數爲60

我認爲,人們普遍認爲,如果包括20爲30或31。

,它顯示了2個月爲我,

「它」?只有一個月。

有很多方法可以確定一個日期是否在另一個月的一個月內,例如,

function withinOneMonth(d0, d1) { 

    // Copy dates so don't affect originals 
    var t0 = new Date(d0); 
    var t1 = new Date(d1); 
    var t; 

    // Get sense right 
    if (t0 > t1) { 
    t = t0; 
    t0 = t1; 
    t1 = t; 
    } 

    // Check if within moth 
    t0.setMonth(t0.getMonth() + 1); 

    // Not inclusive. To make inclusive, use >= 
    return t0 > t1; 
} 
相關問題