Как вы форматируете диапазон дат в Java? - PullRequest
3 голосов
/ 23 августа 2010

У меня есть две даты - начало и конец.Я хотел бы отформатировать их так, чтобы, если месяцы совпадали, они сваливались во что-то вроде «20-23 августа» и по-прежнему форматировались правильно, если они выходят из строя в конце месяца, например, «20 сентября - 1 октября».Существуют ли какие-либо библиотеки для этого или мне нужно было бы передать правила кода для отображения диапазонов дат с использованием отдельных форматов DateFormat?

Ответы [ 5 ]

6 голосов
/ 23 августа 2010

Вот решение, использующее 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 сентября

3 голосов
/ 30 сентября 2010

Я был разочарован другими ответами. Время Joda не работает в GWT, как и SimpleDateFormat. Во всяком случае, я уже знал о DateTimeFormat в GWT. Основная проблема заключается в том, что функция getMonth () объектов date устарела, и не представляется хорошим способом сравнить месяцы и / или годы. Это решение не включает проверку года (которую можно легко добавить, изменив 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;
    }
}
3 голосов
/ 23 августа 2010

Оформить заказ на Java SimpleDateFormat класс. Вы можете создать SimpleDateFormat, передавая шаблон даты в виде строки.

1 голос
/ 23 августа 2010

Чтобы добавить к ответу Йеруна, вы будете использовать SimpleDateFormat дважды, по одному разу для каждого конца диапазона.

0 голосов
/ 23 августа 2010

По умолчанию в Java нет такого типа, как дневной диапазон, поэтому ни один из форматов DateFormat не применим к строковому представлению этого случая.

Лучшим, на мой взгляд, будет создание типа TimeSpan или TimeDiff и метод переопределения для строки. Или, как Вы предложили, создайте DateFormmater, если вам нужно два, также разбора.

...