2012-02-09 59 views
5

约达时间分钟,我有这个简单的代码:的持续时间或间隔

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 

我猜,我做错了什么,我看不出有什么。

回答

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,它实际上是一组字段类型(分钟,月,日等)到值的映射。一段时间内没有单一时间值 - 这是一组值。

+0

哦,我从来没有完全明白这一点。我开悟了。 – 2012-02-09 22:46:27

+2

@LouisWasserman:我在将Joda Time移植到.NET时有点特殊,所以我可能比大多数人对它有更好的理解:) – 2012-02-09 22:49:24

3

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

Period period = new Period(date, currentDate); 
+0

我认为OP关注的是“分钟”中的一个视图给出15,而另一个视图给出1095 ... – 2012-02-09 16:25:22

+0

好点,我现在明白了。 – jbranchaud 2012-02-09 16:28:57