小编典典

将天数分为年,月,日,小时的不同部分。爪哇

java

有没有一种方法可以将通过计算两个日期之间的差异计算出的天数划分为不同的部分,例如对于364天应该是:0年,11个月,30天,小时,分钟等。我认为使用逻辑运算符可能像%和/一样工作,但是由于不同的月份有不同的天数,并且有些年份是leap年,所以我不确定该怎么做。任何帮助将非常感激。我的代码:

import java.util.*;

public class CleanDate {

    public static void main(String[] args) {
        Calendar cDate = GregorianCalendar.getInstance();
        cDate.set(2011, 0, 31, 00, 00, 00);
        Date date1 = cDate.getTime();
        Date date2 = new Date();
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        calendar1.setTime(date1);
        calendar2.setTime(date2);
        long milliseconds1 = calendar1.getTimeInMillis();
        long milliseconds2 = calendar2.getTimeInMillis();
        long diff = milliseconds2 - milliseconds1;
        long diffSeconds = diff / 1000;
        long diffMinutes = diff / (60 * 1000);
        long diffHours = diff / (60 * 60 * 1000);
        long diffDays = diff / (24 * 60 * 60 * 1000);
        System.out.println("Time in minutes: " + diffMinutes + " minutes.");
        System.out.println("Time in hours: " + diffHours + " hours.");
        System.out.println("Time in days: " + diffDays + " days.");
    }
}

阅读 243

收藏
2020-11-30

共1个答案

小编典典

您可以像这样有效地使用Joda Time: Interval允许获取两个日期之间的时间间隔。

DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0);
Interval interval = new Interval(start, end);
Period period = interval.toPeriod();
System.out.println(period.getYears()+" years, "
period.getMonths()+" months, "+period.getWeeks()+" weeks, "+period.getDays()+", days");
2020-11-30