如何在Java中格式化日期范围?

Sor*_*Cat 3 java gwt date-format

我有两个约会 - 开始和结束.我想格式化它们,以便在月份匹配时,它们会崩溃到类似"20-23 AUG"的状态,并且如果它们在月底突破,仍然可以正确格式化,例如"20 SEP - 1 OCT".是否有任何库可用于实现此目的,或者我是否必须使用单独的DateFormats来处理显示日期范围的代码规则?

sta*_*ark 6

这是一个使用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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

8月23日至25日

8月23日至9月5日