user339108
user339108

Reputation: 13101

How to format hours, minutes in AM/PM format

I am trying to format endTime which is available in minutes / hours into AM/PM format. The problematic areas seems to be between 00.00 - 1.00 in the morning and 12.00 - 1.00 in the afternoon. Not sure if this is the right approach or is there a simpler way to accomplish this?

public final String getEndTime() {
    StringBuffer buf = new StringBuffer();
    buf.append(this.getEndTimeInHrs() < 13 ? this.getEndTimeInHrs() : this
            .getEndTimeInHrs() - 13).append(COLON);

    // this check is needed to prefix an additional string in front of the
    // minute (e.g. for 6 hrs 5 minutes, it will be displayed as 6:05)
    if (this.getEndTimeInMinutes() < 10) {
        buf.append(0);
    }
    buf.append(this.getEndTimeInMinutes());

    if (getEndTimeInHrs() < 12) {
        buf.append(SPACE).append(AM);
    } else if (getEndTimeInHrs() > 12) {
        buf.append(SPACE).append(PM);
    }

    return buf.toString();
}

Upvotes: 1

Views: 3990

Answers (2)

Sudhir Jonathan
Sudhir Jonathan

Reputation: 17516

Maybe try (provide your date instead of new Date().

public final String getEndTime() {
    StringBuffer buf = new StringBuffer();
    new SimpleDateFormat("h:m a").format(new Date(), buf, 0);
    return buf.toString();
}

Upvotes: 0

Joey
Joey

Reputation: 354406

What about using a SimpleDateFormat with h:mm a?

E.g.:

DateFormat df = new SimpleDateFormat("h:mm a");
Date date = new Date(0, 0, 0, getHours(), getMinutes());
return df.format(date);

Upvotes: 3

Related Questions