与雅达时间倒数到圣诞节 [英] Count Down to Christmas with Joda-Time
问题描述
我正在尝试执行 Joda-Time 倒数到圣诞节,但到目前为止我感到震惊我尝试java.util.Date和大多数StackOverflow问题和答案建议使用Joda-Time。但我不能让它工作。一些代码给出不同的答案。
I am trying to implement Joda-Time to count down to Christmas, but so far I'm struck. I tried java.util.Date and most StackOverflow questions and answers suggested to use Joda-Time. But I can't get it working. Some codes give different answers.
以下是我尝试的一些代码,
Here are some codes I tried,
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
我出错了?
推荐答案
您应该使用
为了确定涉及的月数/天/等等:
You should be using a Period
in order to determine the number of months/days/etc involved:
Period period = new Period(start, end);
将间隔
转换为一段时间将有一直很好,但是无参数超载包括所有期间单位 - 而您没有打印出这些月份。
Converting an Interval
to a period would have been fine too, but parameterless overload includes all period units - and you weren't printing out the months.
现在,如果你只需要天,小时,分钟,秒,那么您需要创建一个适当的 PeriodType
,例如
PeriodType periodType = PeriodType.dayTime().withMillisRemoved();
Period period = new Period(start, end, periodType);
然后你可以要求这些个人字段,一切都应该很好。
Then you can ask for those individual fields, and all should be well.
(实际上你可以使用 dayTime()
,因为毫无意图干扰别人。)
(You could actually use just dayTime()
, given that the millis won't interfere with anything else.)
所以你可以直接从开始
和 end
建立你的期间或者如果您想保留间隔
,您可以使用:
So you can either build your period directly from the start
and end
as above, or if you want to keep the Interval
, you can use:
Period period = interval.toPeriod(periodType);
这篇关于与雅达时间倒数到圣诞节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!