他这个月过生日了吗?

时间:2011-10-19 08:58:20

标签: javascript

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--;

从2011年8月20日到2011年9月19日,天数为60天,对我来说显示为2个月,但我希望在他的生日one到来之前显示Sept 20th个月。

我提出了上述逻辑,但它不起作用。

2 个答案:

答案 0 :(得分:1)

  

2011年8月20日至2011年9月19日,天数为60

我认为它通常被认为是30或31,如果包括第20个。

  

它显示了我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;
}

答案 1 :(得分: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