Joda持续时间或间隔的时间分钟

我有这个简单的代码:

DateTime date = new DateTime(dateValue); DateTime currentDate = new DateTime(System.currentTimeMillis()); System.out.println("date: " + date.toString()); System.out.println("currentDate: " + currentDate.toString()); Period period = new Period(currentDate, date); System.out.println("PERIOD MINUTES: " + period.getMinutes()); System.out.println("PERIOD DAYS: " + period.getDays()); Duration duration = new Duration(currentDate, date); System.out.println("DURATION MINUTES: " + duration.getStandardMinutes()); System.out.println("DURATION DAYS: " + duration.getStandardDays()); 

我试图找出两个随机日期之间的天数和分钟数。

这是这段代码的输出:

 date: 2012-02-09T00:00:00.000+02:00 currentDate: 2012-02-09T18:15:40.739+02:00 PERIOD MINUTES: -15 PERIOD DAYS: 0 DURATION MINUTES: -1095 DURATION DAYS: 0 

我猜我做错了什么,我只是看不出来。

问题是您没有在句点构造函数中指定句点类型 – 因此它使用默认值“年,月,周,日,小时,分钟,秒和毫秒”。 你只看到15分钟,因为你没有要求几小时,这将返回-18。

如果您只想要几天和几分钟,则应指定:

 PeriodType type = PeriodType.forFields(new DurationFieldType[] { DurationFieldType.days(), DurationFieldType.minutes() }); Period period = new Period(currentDate, date, type); // Now you'll just have minutes and days 

重要的是要理解Duration之间的区别,“ Duration ”是“一定的毫秒数,可以根据不同的单位获取”,而“ Period实际上是从一组字段类型(分钟,月,日等)映射到值。 在一个时期内没有一个单一的时间值 – 它是一组价值观。

看起来它工作得很好,所有你需要做的就是获得正值是交换datecurrentDate

 Period period = new Period(date, currentDate);