与Joda-Time一起倒数圣诞节

Isuru Madusanka:

我正在尝试实施Joda-Time来倒计时到圣诞节,但到目前为止我还是很震惊。我尝试了java.util.Date和大多数建议使用Joda-Time的StackOverflow问题和答案。但是我无法正常工作。一些代码给出了不同的答案。

这是我尝试过的一些代码,

DateTime now = new DateTime();
DateTime christmas = new DateTime(2012, 12, 25, 8, 0, 0, 0);
Days daysToChristmas = Days.daysBetween(today, christmas); 
System.out.println(daysToChristmas.toString());

这将打印P187D作为答案。

DateTime start = new DateTime(DateTime.now());
DateTime end = new DateTime(2012, 12, 25, 0, 0, 0 ,0);
Interval interval = new Interval(start, end);
Period period = interval.toPeriod();
System.out.println("Seconds " + period.getSeconds());
System.out.println("Minutes " + period.getMinutes());
System.out.println("Hours " + period.getHours());
System.out.println("Days " + period.getDays());

这会打印以下结果,

Seconds 36
Minutes 21
Hours 7
Days 4

我哪里出问题了?

乔恩·斯基特(Jon Skeet):

您应该使用a Period来确定所涉及的月/天/等的数量:

Period period = new Period(start, end);

Intervala 转换为周期也可以,但是无参数重载包括所有周期单位-并且您没有打印月份。

现在,如果您需要几天,几小时,几分钟,几秒钟,那么您需要创建一个适当的PeriodType,例如

PeriodType periodType = PeriodType.dayTime().withMillisRemoved();
Period period = new Period(start, end, periodType);

然后,您可以要求这些单独的字段,一切都应该很好。

(实际上dayTime()您可以使用just ,因为毫不影响其他任何东西。)

因此,您可以直接从startend如上构建周期,或者如果要保留Interval,则可以使用:

Period period = interval.toPeriod(periodType);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章