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)
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
If you want the output in prettier format then you can use this snippet too
val startDate = DateTime.now()
val endDate = DateTime(endTime)
val period = Period(startDate, endDate)
val periodFormatter = PeriodFormatterBuilder().apply {
when {
period.days > 0 -> appendDays().appendSuffix(" day", " days")
period.hours > 0 -> appendHours().appendSuffix(" hour", " hours")
period.minutes > 0 -> appendMinutes().appendSuffix(" minute", " minutes")
}
}.toFormatter()
periodFormatter.print(period)