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

TGM*_*TGM 5 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());
Run Code Online (Sandbox Code Playgroud)

我想简单地找出两个随机日期之间的天数和分钟数.

这是这段代码的输出:

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
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 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
Run Code Online (Sandbox Code Playgroud)

重要的是要理解Duration"一定的毫秒数,可以根据不同的单位获取"之间的差异,以及Period实际上是从一组字段类型(分钟,月,日等)到值的映射.一段时间内没有一个单一的时间值 - 它是一组价值观.

  • @LouisWasserman:我在将Joda Time移植到.NET时遇到了一些特殊情况,所以我对它的理解可能比大多数都要好:) (2认同)