JavaScript:如何根据月份计算两个日期的天数

时间:2014-08-26 08:03:48

标签: javascript date date-range

例如,

var from_date = new Date('2014-8-28');
var to_date = new Date('2014-9-3');

从这两个日期范围来看,我需要计算不。基于月的天数。

我怎么能得到这个?

我的预期结果是,

[
  {
    "month" : 8,
    "days"  : 4  // In month of August 28, 29, 30 & 31 has totally 4 days
  },
  {
    "month" : 9,
    "days"  : 3  // In month of September 1, 2 & 3 has totally 3 days
  }
]

提前致谢。

1 个答案:

答案 0 :(得分:2)

本着教学精神,见评论:

var stopDate = new Date("2014-09-04");  // One day AFTER the last date we care
                                        // about
var results = [];                       // An array for our results, initially
                                        // empty
var date = new Date("2014-08-28");      // Our starting date
var entry;                              // The "current" month's entry in the loop
while (date < stopDate) {

    // Create a new entry if necessary.
    // The `!entry` bit uses the fact that variables start out with the value
    // `undefined`, and `undefined` is "falsey", so `!entry` will be true if
    // we haven't put anything in `entry` yet. If we have, it's an object
    // reference, and object references are "truthy", so `!entry` will be
    // false. The second check is to see whether we've moved to a new month.
    if (!entry || entry.month !== date.getMonth() + 1) {

        // Create a new entry. This creates an object using an object initialiser
        // (sometimes called an object "literal")
        entry = {
            month: date.getMonth() + 1, // +1 because `getMonth` uses 0 = January
            days:  0                    // Haven't counted any days yet
        };

        // Add it to the array
        results.push(entry);
    }

    // Count this day
    ++entry.days;

    // Move to next day
    date.setDate(date.getDate() + 1);   // JavaScript's `Date` object handles
                                        // moving to the next month for you
}

关于“falsey”和“truthy”:在大多数语言中,您只能使用布尔值(true或false)进行分支,但JavaScript允许将值强制转换为布尔值。 “Falsey”值是强制为false的值。它们是:undefinednullNaN0"",当然还有false。 “Truthy”的价值观就是其他一切。