當你減去兩個日期對象,其結果是在毫秒之差。它等同於:
a.getTime() - b.getTime();
如果你想在年,月,日的不同,這是一個不同的命題,因爲你不能直接由於大毫秒值轉換爲天的長度之差(可能是1小時夏令時變更時間更長或更短),月(可能包括28至31天)和年(閏年和非閏年)。
下面的腳本是爲計算時代,但它可以很容易地適應你的目的:
// Given a date object, calcualte the number of
// days in the month
function daysInMonth(d) {
return (new Date(d.getFullYear(), (d.getMonth() + 1), 0)).getDate();
}
/* For person born on birthDate, return their
** age on datumDate.
**
** Don't modify original date objects
**
** tDate is used as adding and subtracting
** years, months and days from dates on 29 February
** can affect the outcome,
**
** e.g.
**
** 2000-02-29 + 1 year => 2001-03-01
** 2001-03-01 - 1 year => 2000-03-01 so not symetric
**
** Note: in some systems, a person born on 29-Feb
** will have an official birthday on 28-Feb, other
** systems will have official birthday on 01-Mar.
*/
function getAge(birthDate, datumDate) {
// Make sure birthDate is before datumDate
if (birthDate - datumDate > 0) return null;
var dob = new Date(+birthDate),
now = new Date(+datumDate),
tDate = new Date(+dob),
dobY = dob.getFullYear(),
nowY = now.getFullYear(),
years, months, days;
// Initial estimate of years
years = nowY - dobY;
dobY = (dobY + years);
tDate.setYear(dobY);
// Correct if too many
if (now < tDate) {
--years;
--dobY;
}
dob.setYear(dobY);
// Repair tDate
tDate = new Date(+dob);
// Initial month estimate
months = now.getMonth() - tDate.getMonth();
// Adjust if needed
if (months < 0) {
months = 12 + months;
} else if (months == 0 && tDate.getDate() > now.getDate()) {
months = 11;
}
tDate.setMonth(tDate.getMonth() + months);
if (now < tDate) {
--months;
dob.setMonth(tDate.getMonth() - 1);
}
// Repair tDate
tDate = new Date(+dob);
// Initial day estimate
days = now.getDate() - tDate.getDate();
// Adjust if needed
if (days < 0) {
days = days + daysInMonth(tDate);
}
dob.setDate(dob.getDate() + days);
if (now < dob) {
--days;
}
return years + 'y ' + months + 'm ' + days + 'd';
}
僅供參考,這將是-90不是90 – George 2013-04-29 13:46:05
我編輯的問題 – 2013-04-29 13:47:09
http://stackoverflow.com/questions/5351483/calculate-date-time-difference-in-java – 2013-04-29 13:47:11