Count Up Christmas Yoda Time

I am trying to implement Joda-Time to count down until Christmas, but so far I am amazed. I tried java.util.Date and most of the StackOverflow questions and answers suggesting using Joda-Time. But I can’t make it work. 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()); 

And that prints the P187D as an answer.

 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()); 

And this prints the following result,

 Seconds 36 Minutes 21 Hours 7 Days 4 

Where am I wrong?

+5
source share
3 answers

You must use Period to determine the number of months / days / etc .:

 Period period = new Period(start, end); 

Converting Interval to a period would also be nice, but inconspicuous overloading includes all units of the period - and you did not print the months.

Now, if you only need days, hours, minutes, seconds, you need to create the corresponding PeriodType , for example

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

Then you can request these individual fields, and everything should be fine.

(In fact, you can only use dayTime() , given that millis will not interfere with anything else.)

So, you can either build your period directly from start , and end , as described above, or if you want to keep Interval , you can use:

 Period period = interval.toPeriod(periodType); 
+11
source

The first code prints the P187D in ISO 8601 format .

The second code only prints 4 days because you are missing months ( period.getMonths() ).

+2
source

You can use this code.

 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); 
+2
source

All Articles