如何根据月从两个日期计算天数

JavaScript : How to calculate days count from two dates based on month

本文关键字:两个 日期 计算 何根      更新时间:2023-09-26

例如

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

从这两个日期范围,我需要计算no。按月计算的天数。

我怎样才能得到这个?

我的预期结果是,

[
  {
    "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
  }
]

本着教学精神,见评语:

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
}

关于"false "answers" true ":在大多数语言中,你只能使用布尔值(true或false)进行分支,但JavaScript允许将值强制为布尔值。"假"值是强制为假的值。它们是:undefined, null, NaN, 0, "",当然还有false