omega omega - 2 months ago 16
Android Question

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.

Answer

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