如何更改日期列表以包括前导零(0)

时间:2019-01-16 12:47:31

标签: java date datetime simpledateformat

我正在尝试按升序或降序对日期列表进行排序。但是,我的日期格式为1/12/2020,而不是01/12/2020。如何更改此列表,以使日期采用正确的格式?我在下面提供了一个日期示例:

Actual -    1/12/2020, 1/5/2020, 12/29/2019, 12/22/2019, 12/15/2019
Expected - 01/12/2020, 01/05/2020, 12/29/2019, 12/22/2019, 12/15/2019

我当前的代码是:

public static void assertSortedDates(Grid grid, String header, String format, boolean isAscending) throws Exception {
List<String> original = new ArrayList<String>();
original = grid.getColumn(header);
// if cannot find header try second row of headers
if (original == null) {
    original = grid.getColumnSubtext(header);
}
Collections.replaceAll(original, null, "1 Jan 1901");
Collections.replaceAll(original, "", "1 Jan 1901");
List<String> sorted = DateHelper.sortDates(original, format, isAscending);
assertEquals("Cell Date column is not sorted: " + header + " expected: \n" + sorted + "\nbut got:\n" + original, sorted, original);
}

下面的sortDates代码:

public static List<String> sortDates(List<String> dates, String format, boolean isAscending) throws ParseException{
    List<String> sortedDates = new ArrayList<>();
    SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);

    // convert to date
    Date[] arrayOfDates = new Date[dates.size()];

    for (int i = 0; i < dates.size(); i++) {
        arrayOfDates[i] = sdf.parse(dates.get(i));
    }

    // sort
    if (isAscending) {
        Arrays.sort(arrayOfDates);
    } else {
        Arrays.sort(arrayOfDates, Collections.reverseOrder());
    }

    // convert back to String
    for (int index = 0; index < arrayOfDates.length; index++) {
        sortedDates.add(sdf.format(arrayOfDates[index]));
    }
    return sortedDates;
}

编辑:我已经在我的sortOnCallSummary方法上设置了日期格式MM / dd / yyyy,该方法调用assertSortedDates方法。我认为我还需要在某个地方格式化原始列表,但是我不确定在哪里进行格式化。

private void sortOnCallSummary() throws Exception {
    Grid grid;
    String[] headersAllJobs = { "From", "To", "RHVAC Technician Schedules Complete", "MST Schedules Complete" };
    for (String header : headersAllJobs) {
        scrollTo(0);
        runtimeState.onCallSummaryPage.tableSort(header, RandomUtils.nextBoolean());
        boolean isAscending = runtimeState.onCallSummaryPage.isAscending(header);
        outputHelper.takeScreenshot();
        grid = runtimeState.onCallSummaryPage.getGrid();
        String order = isAscending ? "ascending" : "descending";
        runtimeState.scenario.write("Asserting " + header + " column is sorted in " + order + " order");

        switch (header) {
        case "From":
        case "To":
            GridHelper.assertSortedDates(grid, header, "MM/dd/yyyy", isAscending);
            break;
        case "RHVAC Technician Schedules Complete":
        case "MST Schedules Complete":
        default:
            GridHelper.assertSortedAlphabetic(grid, header, isAscending);
            break;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您应该使用最新的java.time API,然后只需解析为LocalDate并使用内置排序即可:

  • 将其称为:sortDates(datesStr, "M/d/yyyy", true);
static List<LocalDate> sortDates(List<String> datesStr, String format, boolean isAscending) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
    List<LocalDate> dates = new ArrayList<>();
    for (String str : datesStr) {
        LocalDate date = LocalDate.parse(str, formatter);
        dates.add(date);
    }
    dates.sort(isAscending ? Comparator.naturalOrder() : Comparator.reverseOrder());
    return dates;
}

以流的方式看起来像

static List<LocalDate> sortDates(List<String> datesStr, String format, boolean isAscending) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
    return datesStr.stream()
                   .map(str -> LocalDate.parse(str, formatter))
                   .sorted(isAscending ? Comparator.naturalOrder() : Comparator.reverseOrder())
                   .collect(Collectors.toList());
}