关于java:如何使用Joda-Time计算两年中两个日期之间的差异…等

How to calculate difference between two dates in years…etc with Joda-Time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.text.SimpleDateFormat;
import java.util.Date;
import org.joda.time.*;

public class Test {

  public static void main(String[] args) {

String dateStart ="01/01/2000 05:30";
String dateStop ="02/2/2001 06:31";

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm");

Date d1 = null;
Date d2 = null;

try {
    d1 = format.parse(dateStart);
    d2 = format.parse(dateStop);

    DateTime dt1 = new DateTime(d1);
    DateTime dt2 = new DateTime(d2);

    System.out.print(Years.yearsBetween(dt1, dt2).getYears() +" years,");
    System.out.print(Months.monthsBetween(dt1, dt2).getMonths() % 52 +" months,");
    System.out.print(Weeks.weeksBetween(dt1, dt2).getWeeks() % 4 +" weeks,");
    System.out.print(Days.daysBetween(dt1, dt2).getDays() % 7 +" days,");
    System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 +" hours,");
    System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 +" minutes,");


 } catch (Exception e) {
    e.printStackTrace();
 }

}

}

我想使用joda time输出两个日期之间的年、月、周、天、小时和分钟数。我的问题是,我在哪里实现一个月内的周数(这永远不会是常量)。我也不认为我的百分比是对的。

运行时,我得到:

1
1 years, 13 months, 0 weeks, 6 days, 1 hours, 1 minutes,


Period是现成的。

1
2
3
4
Period period = new Period(d1, d2);
System.out.print(period.getYears() +" years,");
System.out.print(period.getMonths() +" months,");
// ...

为了美化和获得对输出的更多控制,您可以使用PeriodFormatterBuilder