ZahidRasheed
11/23/2016 - 12:24 AM

JodaTimeUtils.Java

public final class JodaTimeUtils {
    public static String formatStringToHoursAndMinutes(String timestamp, Locale locale) {
        DateTime dt = (ISODateTimeFormat.dateTime()).parseDateTime(timestamp);
        return dt.toString("HH:mm", locale);
    }

    public static String getDurationBetween(String start, String end) {
        DateTime startDate = (ISODateTimeFormat.dateTime()).parseDateTime(start);
        DateTime endDate = (ISODateTimeFormat.dateTime()).parseDateTime(end);
        return getDurationBetweenTwoDates(startDate, endDate);
    }

    public static String getDurationBetweenTwoDates(DateTime startDate, DateTime endDate) {
        PeriodFormatter fmt = new PeriodFormatterBuilder()
                .printZeroNever()
                .appendHours()
                .appendSuffix("h ")
                .appendMinutes()
                .appendSuffix("m")
                .toFormatter();
        return fmt.print(new Period(startDate, endDate));
    }
  
  public static String getFormattedExpiryDate(String startDate, String endDate) {
        Period period = new Period((ISODateTimeFormat.dateTime()).parseDateTime(startDate),
                                   (ISODateTimeFormat.dateTime()).parseDateTime(endDate),
                                   PeriodType.yearMonthDayTime());
        PeriodFormatter formatter = new PeriodFormatterBuilder()
                .appendYears()
                .appendSuffix(" year "," years ")
                .appendMonths()
                .appendSuffix(" month "," months ")
                .appendDays()
                .appendSuffix(" day "," days ")
                .appendHours()
                .appendSuffix(" hour ","hours ")
                .appendMinutes()
                .appendSuffix(" minute "," minutes ")
                .appendSeconds()
                .appendSuffix(" second "," seconds ")
                .toFormatter();
        return formatter.print(period);
    }
}