这是一个使用
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());
}
}
}
输出:
8月23日至25日
8月23日至9月5日