Вот решение, использующее JodaTime , лучшую библиотеку для работы с датами в Java (последний раз, когда я проверял). Форматирование простое и, несомненно, может быть улучшено с помощью пользовательских реализаций DateFormatter. Это также проверяет, что год совпадает, но не выводит год, что может сбить с толку.
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 сентября