Here's a solution using JodaTime - the best library for working with dates in Java (the last time I checked). Formatting is simple and can no doubt be improved by using custom DateFormatter implementations. It also checks that the year is the same, but does not deduce the year, which can be confusing.
import org.joda.time.DateTime;
public class DateFormatterTest {
public static void main(String[] args) {
DateTime august23rd = new DateTime(2010, 8, 23, 0, 0, 0, 0);
DateTime august25th = new DateTime(2010, 8, 25, 0, 0, 0, 0);
DateTime september5th = new DateTime(2010, 9, 5, 0, 0, 0, 0);
DateFormatterTest tester = new DateFormatterTest();
tester.outputDate(august23rd, august25th);
tester.outputDate(august23rd, september5th);
}
private void outputDate(DateTime firstDate, DateTime secondDate) {
if ((firstDate.getMonthOfYear() == secondDate.getMonthOfYear()) && (firstDate.getYear() == secondDate.getYear())) {
System.out.println(firstDate.getDayOfMonth() + " - " + secondDate.getDayOfMonth() + " " + firstDate.monthOfYear().getAsShortText());
} else {
System.out.println(firstDate.getDayOfMonth() + " " + firstDate.monthOfYear().getAsShortText() + " - " + secondDate.getDayOfMonth() + " " + secondDate.monthOfYear().getAsShortText());
}
}
}
:
23 - 25
23 - 5