我需要找出从现在到未来使用 Java 的月数、周数、天数和小时数。我不能使用像 Joda 这样的第三方库。如何仅使用 JDK 类来做到这一点?
到目前为止,这就是我想出的。它有点工作,除了某些情况:
public class DateUtil {
public static Integer[] components(Date from, Date to) {
Integer[] result = new Integer[4];
//SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//df.setTimeZone(TimeZone.getTimeZone("EST"));
Calendar fromCal = new GregorianCalendar();
Calendar toCal = new GregorianCalendar();
fromCal.setTime(from);
toCal.setTime(to);
int months = 0;
do {
fromCal.add(Calendar.MONTH, 1);
++months;
//System.out.println(df.format(fromCal.getTime()));
} while (fromCal.before(toCal));
fromCal.add(Calendar.MONTH, -1);
--months;
int days = 0;
do {
fromCal.add(Calendar.DAY_OF_YEAR, 1);
++days;
} while (fromCal.before(toCal));
fromCal.add(Calendar.DAY_OF_YEAR, -1);
--days;
int hours = 0;
do {
fromCal.add(Calendar.HOUR_OF_DAY, 1);
++hours;
} while (fromCal.before(toCal));
fromCal.add(Calendar.HOUR_OF_DAY, -1);
--hours;
int minutes = 0;
do {
fromCal.add(Calendar.MINUTE, 1);
++minutes;
} while (fromCal.before(toCal));
result[0] = months;
result[1] = days;
result[2] = hours;
result[3] = minutes;
return result;
}
public static void main(String[] args) {
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
df.setTimeZone(TimeZone.getTimeZone("EST"));
Date from = df.parse("2014-03-29 00:00");
Date to = df.parse("2014-05-29 00:00");
Integer result[] = components(from, to);
System.out.printf("Months:%02d Days:%02d Hrs:%02d Mins:%02d\n",
result[0], result[1], result[2], result[3]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
当二月在中间并且开始日期是月底时,它会产生不可接受的结果。例如:
自:2013 年 12 月 31 日至:2014 年 12 月 31 日
差异将产生:12个月,3天。