我正在努力实施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
我哪里出错?
答案 0 :(得分:12)
您应该使用Period
来确定所涉及的月/日/等的数量:
Period period = new Period(start, end);
将Interval
转换为句点也可以,但无参数重载包括所有期间单位 - 并且您没有打印出月份。
现在,如果你只想要几天,几小时,几分钟,几秒钟,那么你需要创建一个合适的PeriodType
,例如
PeriodType periodType = PeriodType.dayTime().withMillisRemoved();
Period period = new Period(start, end, periodType);
然后你可以要求那些单独的领域,一切都应该很好。
(实际上你可以使用dayTime()
,因为millis不会干扰任何其他事情。)
因此,您可以直接从上面的start
和end
构建句点,或者如果您想保留Interval
,则可以使用:
Period period = interval.toPeriod(periodType);
答案 1 :(得分:2)
第一个代码以ISO 8601格式打印 P187D 。
第二个代码仅打印4天,因为您错过了几个月(period.getMonths()
)。
答案 2 :(得分:2)
您可以使用此代码。
DateTime dt1 = new DateTime();
DateTime dt2 = new DateTime(2012, 12, 25, 0, 0, 0, 0);
int seconds=Seconds.secondsBetween(dt1, dt2).getSeconds();
int noOfDays=seconds/(24*60*60);
int noOfHours=(seconds%(24*60*60))/(60*60);
int noOfMinutes=((seconds%(24*60*60))%(60*60))/60;
int noSec=((seconds%(24*60*60))%(60*60))%60;
System.out.println("Time Left For christmas");
System.out.println("Days Left="+noOfDays+" Hours="+noOfHours+" Minutes="+noOfMinutes+" Seconds="+noSec);