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

时间:2012-02-09 16:20:25

标签: java date

我有这个简单的代码:

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

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

2 个答案:

答案 0 :(得分:13)

问题在于您没有在句点构造函数中指定句点类型 - 因此它使用默认值“年,月,周,日,小时,分钟,秒和毫秒”。你只看到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之间的差异很重要,Period是“一定的毫秒数,可以根据不同的单位获取”,而{{1}}实际上是一组映射的{{1}}字段类型(分钟,月,日等)到值。一段时间内没有一个时间值 - 它是一组值。

答案 1 :(得分:3)

看起来它工作正常,只需交换datecurrentDate即可获得正值的所有内容:

Period period = new Period(date, currentDate);