Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format date range in java?

In java, I have two calendar objects that contain a date and time. Both calendar objects are on same day but will have different times. How can I format it to look like this example:

Wednesday, November 8, 2013 10:00AM-11:00AM

Thanks.

like image 217
omega Avatar asked Aug 07 '26 07:08

omega


2 Answers

You should use a SimpleDateFormat to do it, here are the docs and an example:

String dFormat = "EEEE, MMMM d, yyyy",
       tFormat = "KK:mm a";

public String formatInterval(Date from, Date to) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(dFormat),
                     timeFormat = new SimpleDateFormat(tFormat);

    StringBuilder s = new StringBuilder();
    // Day
    s.append(dateFormat.format(from));
    s.append(' ');
    // Start time
    s.append(timeFormat.format(from));
    s.append(" - ");
    // End time
    s.append(timeFormat.format(to));
    return s.toString();
}

public String formatInterval(Calendar from, Calendar to) {
    return formatInterval(from.getTime(), to.getTime());
}
like image 107
Tobias Avatar answered Aug 08 '26 21:08

Tobias


I would recommend the DateUtils:

String range = DateUtils.formatDateRange(mContext, startDate.getMillis(), endDate.getMillis(), DateUtils.FORMAT_ABBREV_TIME);

(starDate and endDate are from jodaTime, if you use "Date" you need to convert it to milliseconds via Calendar)

like image 29
Tino Avatar answered Aug 08 '26 20:08

Tino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!