omega
omega

Reputation: 43833

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.

Upvotes: 3

Views: 2234

Answers (2)

Tino
Tino

Reputation: 299

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)

Upvotes: 1

Tobias
Tobias

Reputation: 7771

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

Upvotes: 3

Related Questions