首页 > 解决方案 > Java:如何获得匹配模式的下一次

问题描述

是否有一种简单/直接的方法可以使用 DateTimeFormatter 模式来获取与该模式匹配的下一个 LocalDateTime 时间?

我想用它来轻松获取下一次事件应该发生的时间(可以是每天、每周、每月等)。例如,如果事件发生在“星期一 12:00 AM”,我想获得下星期一 12:00 AM 的 LocalDateTime。

    /**Get next LocalDateTime that matches this input
     * 
     * @param input a String for time matching the pattern: [dayOfWeek ][dayOfMonth ][month ][year ]<timeOfDay> <AM/PM>
     * @return LocalDateTime representing the next time that matches the input*/
    public LocalDateTime getNextTime(String input) {
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("[eeee ][d ][MMMM ][u ]h:m a");
        TemporalAccessor accessor = format.parse(input);
        // TODO somehow get the next time (that's after currentTime) that matches this pattern
        // LocalDateTime time = ???
        return time;
    }

我不能这样做LocalDateTime.from(accessor),因为输入中可能没有指定年份、月份或月份中的某天。

为了澄清,这里有一些我想要的例子:

// if current date is Friday, January 1st, 2021 at 12:00 PM 

// this should return a LocalDateTime for Monday, January 4th, 2021 12:00 AM
getNextTime("Monday 12:00 AM");

// should return Saturday, January 2nd, 2021 12:00 AM
getNextTime("12:00 AM"); 

// should return Tuesday, January 5th, 2021 12:00 AM
getNextTime("5 January 12:00 AM");

// should return Friday, January 8th, 2021 12:00 PM (must be AFTER current time)
getNextTime("Friday 12:00 PM");

标签: javadatetimedatetimeformatter

解决方案


不,没有一种简单或直接的方法可以满足您的要求。它涉及相当多的编码。您基本上有 16 个案例,因为每年、每月、每月的某一天和每周的某一天都可能出现,也可能不出现。而且您或多或少将不得不分别处理每个案例。

也可能不会有下一次了。如果年份是 2019 年,则没有。如果字符串是Friday 12 January 2021 2:00 AM,则不是因为 1 月 12 日是星期二,而不是星期五。

private static DateTimeFormatter format = DateTimeFormatter
        .ofPattern("[eeee ][uuuu ][d ][MMMM ][uuuu ]h:m a", Locale.ENGLISH);

// input = [dayOfWeek] [dayOfMonth] [month] [year] <timeOfDay> <AM/PM>
public static LocalDateTime next(String text) {
    TemporalAccessor accessor;
    try {
        accessor = format.parse(text);
    } catch (DateTimeParseException dtpe) {
        return null;
    }
    LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
    LocalTime parsedTime = LocalTime.from(accessor);
    LocalDate earliest = now.toLocalDate();
    if (parsedTime.isBefore(now.toLocalTime())) {
        earliest = earliest.plusDays(1);
    }
    return resolveYearMonthDomDow(earliest, accessor).atTime(parsedTime);
}

private static LocalDate resolveYearMonthDomDow(LocalDate earliest, TemporalAccessor accessor) {
    if (accessor.isSupported(ChronoField.YEAR)) {
        Year parsedYear = Year.from(accessor);
        if (parsedYear.isBefore(Year.from(earliest))) {
            return null;
        }
        return resolveMonthDomDow(parsedYear, earliest, accessor);
    } else {
        Year candidateYear = Year.from(earliest);
        while (true) {
            LocalDate resolved = resolveMonthDomDow(candidateYear, earliest, accessor);
            if (resolved != null) {
                return resolved;
            }
            candidateYear = candidateYear.plusYears(1);
        }
    }
}

private static LocalDate resolveMonthDomDow(Year year, LocalDate earliest, TemporalAccessor accessor) {
    if (accessor.isSupported(ChronoField.MONTH_OF_YEAR)) {
        YearMonth knownYm = year.atMonth(accessor.get(ChronoField.MONTH_OF_YEAR));
        if (knownYm.isBefore(YearMonth.from(earliest))) {
            return null;
        }
        return resolveDomDow(knownYm, earliest, accessor);
    } else {
        YearMonth candidateYearMonth = YearMonth.from(earliest);
        if (candidateYearMonth.getYear() < year.getValue()) {
            candidateYearMonth = year.atMonth(Month.JANUARY);
        }
        while (candidateYearMonth.getYear() == year.getValue()) {
            LocalDate resolved = resolveDomDow(candidateYearMonth, earliest, accessor);
            if (resolved != null) {
                return resolved;
            }
            candidateYearMonth = candidateYearMonth.plusMonths(1);
        }
        return null;
    }
}

private static LocalDate resolveDomDow(YearMonth ym, LocalDate earliest, TemporalAccessor accessor) {
    if (accessor.isSupported(ChronoField.DAY_OF_MONTH)) {
        int dayOfMonth = accessor.get(ChronoField.DAY_OF_MONTH);
        if (dayOfMonth > ym.lengthOfMonth()) {
            return null;
        }
        LocalDate resolved = ym.atDay(dayOfMonth);
        if (resolved.isBefore(earliest)) {
            return null;
        } else {
            return resolveDow(resolved, accessor);
        }
    } else {
        LocalDate candidateDate = earliest;
        if (YearMonth.from(earliest).isBefore(ym)) {
            candidateDate = ym.atDay(1);
        }
        while (YearMonth.from(candidateDate).equals(ym)) {
            LocalDate resolved = resolveDow(candidateDate, accessor);
            if (resolved != null) {
                return resolved;
            }
            candidateDate = candidateDate.plusDays(1);
        }
        return null;
    }
}

private static LocalDate resolveDow(LocalDate date, TemporalAccessor accessor) {
    if (accessor.isSupported(ChronoField.DAY_OF_WEEK)) {
        if (date.getDayOfWeek().getValue() == accessor.get(ChronoField.DAY_OF_WEEK)) {
            return date;
        } else {
            return null;
        }
    } else {
        return date;
    }
}

让我们试一试:

    String input = "Monday 12:00 AM";
    // get the next time that matches this pattern
    LocalDateTime time = next(input);
    System.out.println(time);

刚才跑的时候输出(2021年1月11日星期一晚上):

2021-01-18T00:00

所以下周一。看起来不错。

举一个不同的例子,表明闰年得到尊重:

    String input = "Wednesday 29 February 12:00 AM";

2040-02-29T00:00

我的代码中很可能存在错误,但基本思想是有效的。

一天中的时间没有问题。挑战在于日期。我正在使用一天中的时间来确定今天的日期是否是最早的候选人。如果现在的时间已经超过了字符串中的时间,那么最早的可能日期就是明天。对于您的示例字符串,Monday 12:00 AM实际上总是如此:它总是在午夜 12 点之后。

Monday 25 12:00 AM由于 25 可能是一年(几千年前)或一个月中的一天,因此您一直模棱两可。我通过坚持四位数的年份解决了这个问题。因此,如果一个数字在一周中某一天的开头或之后有四位数字,则为一年,否则为一个月中的某一天。我使用的格式化程序看起来很有趣,一年来了两次。我需要这个来强制解析在尝试每月的某天之前尝试一年,否则有时需要一个四位数的数字作为月份的某天。这反过来意味着格式化程序接受的格式太多了。我认为这在实践中不会成为问题。


推荐阅读