簡體   English   中英

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

[英]How do you format a date range in Java?

我有兩個約會 - 開始和結束。 我想格式化它們,以便在月份匹配時,它們會崩潰到類似“20-23 AUG”的狀態,並且如果它們在月底突破,仍然可以正確格式化,例如“20 SEP - 1 OCT”。 是否有任何庫可用於實現此目的,或者我是否必須使用單獨的DateFormats來處理顯示日期范圍的代碼規則?

這是一個使用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日

Checkout java的SimpleDateFormat類。 您可以構造一個SimpleDateFormat,將日期模式作為String傳遞。

我對其他答案感到失望。 Joda時間在GWT中不起作用,SimpleDateFormat也不起作用。 無論如何,我已經知道了GWT中的DateTimeFormat。 主要問題是不推薦使用日期對象getMonth()函數,並且似乎沒有一種比較月和/或年的好方法。 此解決方案不包括年度檢查(可以通過更改monthFormatter輕松添加),但這對我的情況並不重要。

public final class DateUtility
{
    public static final DateTimeFormat MONTH_FORMAT = DateTimeFormat.getFormat("MMM");
    public static final DateTimeFormat DAY_FORMAT = DateTimeFormat.getFormat("dd");
    public static final DateTimeFormat DAY_MONTH_FORMAT = DateTimeFormat.getFormat("dd MMM");

    public static final String DASH = " - ";

    /**
     * Returns a "collapsed" date range String representing the period of time
     * between two Date parameters. Example: August 19 as a {@code startDate}
     * and August 30 as an {@code endDate} will return "19 - 30 AUG", August 28
     * as a {@code startDate} and September 7 as an {@code endDate} will return
     * "28 AUG - 07 SEP". This means if you pass this two dates which cannot
     * collapse into a shorter form, then the longer form is returned.  Years
     * are ignored, and the start and end dates are not checked to ensure we
     * are not going backwards in time (Aug 10 - July 04 is not checked).
     * 
     * @param startDate
     *            the start Date in the range.
     * @param endDate
     *            the end Date in the range.
     * @return a String representation of the range between the two dates given.
     */
    public static String collapseDate(Date startDate, Date endDate) {
        String formattedDateRange;

        // Get a comparison result to determine if the Months are the same
        String startDateMonth = MONTH_FORMAT.format(startDate);
        String endDateMonth = MONTH_FORMAT.format(endDate);

        if (startDateMonth.equals(endDateMonth))
        {
            formattedDateRange = DAY_FORMAT.format(startDate) + DASH
                    + DAY_MONTH_FORMAT.format(endDate).toUpperCase();
        }
        else
        {
            // Months don't match, split the string across both months
            formattedDateRange = DAY_MONTH_FORMAT.format(startDate).toUpperCase()
                    + DASH + DAY_MONTH_FORMAT.format(endDate).toUpperCase();
        }
        return formattedDateRange;
    }
}

要添加到Jeroen的答案,您將使用兩次SimpleDateFormat,一次用於范圍的每一端。

默認情況下,Java中沒有類型為日期范圍,因此沒有任何DateFormats適用於此情況的字符串表示形式。

我認為最好的是創建類型為TimeSpan或TimeDiff並將方法重寫為字符串。 或者,如果您還需要兩個解析,則建議您創建一個DateFormmater。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM