Reputation: 4089
I'd like to format a date to include a special "part of day" indicator - for example "midnight" for hour=0, "am" for 0<hour<12, "noon" for hour=12 and "pm" for hour>12.
Since SimpleDateFormat has no such feature, how can I implement it? I could use SimpleDateFormat for the rest of the format and do the part of day separately, but that involves creating a new Calendar object, calculating the part of day and stitching results together. That feels quite awkward and inefficient.
Ideally I'd like to "plug in" my "part of day" formatter into SimpleDateFormat or some other date formatter (if it's possible with joda-time, I'm interested too).
Upvotes: 0
Views: 1770
Reputation: 61168
I would use a ChoiceFormat
for the custom output and a DateFormat
for the rest. This can be combined quite elegantly using a MessageFormat
.
final String format = "{0,choice,0#midnight|0<am|12#noon|12<pm} {1,date,dd MMM YYYY HH:mm:ss}";
final MessageFormat messageFormat = new MessageFormat(format);
Example:
public static void main(String args[]) {
final Calendar calendar = Calendar.getInstance();
final String format = "{0,choice,0#midnight|0<am|12#noon|12<pm} {1,date,dd MMM YYYY HH:mm:ss}";
final MessageFormat messageFormat = new MessageFormat(format);
System.out.println(messageFormat.format(new Object[]{calendar.get(Calendar.HOUR_OF_DAY), calendar.getTime()}));
System.out.println("==== TESTS ====");
calendar.set(Calendar.HOUR_OF_DAY, 0);
System.out.println(messageFormat.format(new Object[]{calendar.get(Calendar.HOUR_OF_DAY), calendar.getTime()}));
calendar.set(Calendar.HOUR_OF_DAY, 1);
System.out.println(messageFormat.format(new Object[]{calendar.get(Calendar.HOUR_OF_DAY), calendar.getTime()}));
calendar.set(Calendar.HOUR_OF_DAY, 11);
System.out.println(messageFormat.format(new Object[]{calendar.get(Calendar.HOUR_OF_DAY), calendar.getTime()}));
calendar.set(Calendar.HOUR_OF_DAY, 12);
System.out.println(messageFormat.format(new Object[]{calendar.get(Calendar.HOUR_OF_DAY), calendar.getTime()}));
calendar.set(Calendar.HOUR_OF_DAY, 14);
System.out.println(messageFormat.format(new Object[]{calendar.get(Calendar.HOUR_OF_DAY), calendar.getTime()}));
}
Output:
am 08 Nov 2013 08:53:58
==== TESTS ====
midnight 08 Nov 2013 00:53:58
am 08 Nov 2013 01:53:58
am 08 Nov 2013 11:53:58
noon 08 Nov 2013 12:53:58
pm 08 Nov 2013 14:53:58
Upvotes: 2