2

2つの日付の違いを見つけたいです。そのために、ある Date オブジェクトから別の Date オブジェクトを減算しました。私のコードは次のとおりです。

var d1 = new Date(); //"now"
var d2 = new Date(2012,3,17); // before one year
document.write("</br>Currrent date : "+d1);
document.write("</br>Other Date : "+d2);
document.write("</br>Difference : "+new Date(Math.abs(d1-d2)));

しかし、結果は期待どおりではありません。

現在の日付: 2013 年 2 月 17 日日曜日 02:58:16 GMT-0500 (EST)
その他の日付: 2012 年 1 月 21 日土曜日 00:00:00 GMT-0500 (EST)
差異: 1971 年 1 月 28 日木曜日 21:58:16 GMT-0500 (EST(東部基準時)

それらの間の(1年)差を計算したい。

ありがとう

4

4 に答える 4

4

したがって、基本的に最大の正確な日付単位は7 * 86400 秒を占める1 週間です。月と年は厳密には定義されていません。5.1.2013したがって、2 つの日付がたとえばand5.2.2013または5.2.2013andの場合、「1 か月前」と言いたいとします5.3.2013。そして、「1 か月と 1 日前」と言うと、例えば5.1.2013and6.2.2013がある場合、次のような計算を使用する必要があります。

// dateFrom and dateTo have to be "Date" instances, and to has to be later/bigger than from.
function dateDiff(dateFrom, dateTo) {
  var from = {
    d: dateFrom.getDate(),
    m: dateFrom.getMonth() + 1,
    y: dateFrom.getFullYear()
  };

  var to = {
    d: dateTo.getDate(),
    m: dateTo.getMonth() + 1,
    y: dateTo.getFullYear()
  };

  var daysFebruary = to.y % 4 != 0 || (to.y % 100 == 0 && to.y % 400 != 0)? 28 : 29;
  var daysInMonths = [0, 31, daysFebruary, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  if (to.d < from.d) {
    to.d   += daysInMonths[parseInt(to.m)];
    from.m += 1;
  }
  if (to.m < from.m) {
    to.m   += 12;
    from.y += 1;
  }

  return {
    days:   to.d - from.d,
    months: to.m - from.m,
    years:  to.y - from.y
  };
}
// Difference from 1 June 2016 to now
console.log(dateDiff(new Date(2016,5,1), new Date()));

私が言ったように、それはトリッキーになります;)

于 2013-02-17T09:04:54.313 に答える
4

かなり正確にする必要がある場合は、単位として日を使用することをお勧めします。年と月の日数は可変であるため、「1 か月」または「1 年」と言うと、異なる日数を意味する場合があります。

var d1 = new Date(); //"now"
var d2 = new Date(2012,3,17); // before one year
var msPerDay = 1000*60*60*24;
document.write( ((d1 - d2) / msPerDay).toFixed(0) + " days ago");
于 2013-02-17T08:41:09.023 に答える
2

これを探していますか?

 Math.ceil((new Date(2012, 11, 23) - new Date(2012, 11, 21)) / 86400000) + 1
于 2013-02-17T08:20:29.047 に答える
0

これを探していますか?

Math.ceil((新しい日付(2012, 11, 23) - 新しい日付(2012, 11, 21)) / 864000) + 1

于 2014-05-27T05:35:37.147 に答える