Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Remaining day and time using jodatime

I want to compare(finding remaining days and time between two days) using joda time. I am taking two DateTime object like this(one is starting and another is ending)

DateTime endDate  = new DateTime(2011,12,25,0,0,0,0);   
DateTime strtDate = new DateTime();

Now i am interested to find remaining date and time like this days:49 Hrs:5 Min:52 Sec:45(Not considering Year and month here..)

Now I go ahead with period class like this

Period period = new Period();

PeriodFormatter formatter = new PeriodFormatterBuilder()
    .appendSeconds()
    .appendMinutes()
    .appendHours()
    .appendDays()
    .appendMonths()
    .appendYears()
    .printZeroNever()
    .toFormatter();

Now in result what i get year,month,Day,etc... in this case i will get days between 1-30(not 31,45,49...(which I want)) always.

So how can i get this thing(is there any method that I am missing) or I need to handle this programmatically, as I read that joda time is very flexible so I am very sure that there will be any method like this.

If you are familiar then kindly share your knowledge.

like image 233
Roshan Jha Avatar asked Dec 09 '22 04:12

Roshan Jha


1 Answers

Defines all standard fields from days downwards with PeriodType.dayTime().

For example :

DateTime startDate = DateTime.now(); // now() : since Joda Time 2.0
DateTime endDate = new DateTime(2011, 12, 25, 0, 0);

Period period = new Period(startDate, endDate, PeriodType.dayTime());

PeriodFormatter formatter = new PeriodFormatterBuilder()
        .appendDays().appendSuffix(" day ", " days ")
        .appendHours().appendSuffix(" hour ", " hours ")
        .appendMinutes().appendSuffix(" minute ", " minutes ")
        .appendSeconds().appendSuffix(" second ", " seconds ")
        .toFormatter();

System.out.println(formatter.print(period));

Sample output

Period between startDate and endDate is

47 days 12 hours 46 minutes 47 seconds


Or

PeriodFormatter formatter = new PeriodFormatterBuilder()
        .appendPrefix("Day:", " Days:").appendDays()
        .appendPrefix(" Hour:", " Hours:").appendHours()
        .appendPrefix(" Minute:", " Minutes:").appendMinutes()
        .appendPrefix(" Second:", " Seconds:").appendSeconds()
        .toFormatter();

with output

Days:47 Hours:12 Minutes:46 Seconds:47

like image 170
lschin Avatar answered Dec 21 '22 09:12

lschin