Java:检查当前日期是否在特定日期的范围内

时间:2015-11-13 20:14:52

标签: java datetime

我正在努力解决以下问题:

在我的应用中,我想检查来自LocalDateTime.now()的当前日期时间 在一周中某些特定日期的范围内,假设在星期五星期日之间。

示例:

日期时间窗口从星期五20:00 星期日20:00 。当我在星期四 22:00 *查看当前日期时,答案应该是false,但是当我在**星期六上查看 8时: 00 ,答案应为true

我可以使用DayOfWeek API中的java.time类使用compareTo()方法并分别比较小时和分钟来实现此目的,但我想知道是否有更好的方法可以做它,特别是当天数超过两周时(例如星期五到下周的星期一)?

提前感谢任何建议或帮助。

4 个答案:

答案 0 :(得分:3)

由于您要将LocalDateTimeDayOfWeek + LocalTime进行比较,或者更确切地检查它是否在两个DayOfWeek + LocalTime对之间,上课可能会很好:

public final class DayOfWeekTimeRange {
    private final DayOfWeek fromDay;
    private final LocalTime fromTime;
    private final DayOfWeek toDay;
    private final LocalTime toTime;
    private final boolean   inverted;
    public DayOfWeekTimeRange(DayOfWeek fromDay, LocalTime fromTime, DayOfWeek toDay, LocalTime toTime) {
        this.fromDay = fromDay;
        this.fromTime = fromTime;
        this.toDay = toDay;
        this.toTime = toTime;
        this.inverted = compare(this.fromDay, this.fromTime, this.toDay, this.toTime) > 0;
    }
    public boolean inRange(LocalDateTime dateTime) {
        return inRange(dateTime.getDayOfWeek(), dateTime.toLocalTime());
    }
    public boolean inRange(DayOfWeek day, LocalTime time) {
        boolean fromOk = compare(day, time, this.fromDay, this.fromTime) >= 0; // Lower-inclusive
        boolean toOk   = compare(day, time, this.toDay  , this.toTime  ) <  0; // Upper-exclusive
        return (this.inverted ? fromOk || toOk : fromOk && toOk);
    }
    private static int compare(DayOfWeek day1, LocalTime time1, DayOfWeek day2, LocalTime time2) {
        int cmp = day1.compareTo(day2);
        if (cmp == 0)
            cmp = time1.compareTo(time2);
        return cmp;
    }
}

测试

// Fri 10:00 PM  to  Sun 10:00 PM
DayOfWeekTimeRange range = new DayOfWeekTimeRange(DayOfWeek.FRIDAY, LocalTime.of(20,0), DayOfWeek.SUNDAY, LocalTime.of(20,0));
System.out.println(range.inRange(LocalDateTime.of(2015, 11, 12, 22, 0))); // Thu Nov. 12 2015 at 10:00 PM
System.out.println(range.inRange(LocalDateTime.of(2015, 11, 14,  8, 0))); // Sat Nov. 14 2015 at  8:00 AM
System.out.println(range.inRange(LocalDateTime.of(2015, 11, 16, 15, 0))); // Mon Nov. 16 2015 at  3:00 PM

// Fri 10:00 PM  to  Mon 10:00 PM
range = new DayOfWeekTimeRange(DayOfWeek.FRIDAY, LocalTime.of(20,0), DayOfWeek.MONDAY, LocalTime.of(20,0));
System.out.println(range.inRange(LocalDateTime.of(2015, 11, 12, 22, 0))); // Thu Nov. 12 2015 at 10:00 PM
System.out.println(range.inRange(LocalDateTime.of(2015, 11, 14,  8, 0))); // Sat Nov. 14 2015 at  8:00 AM
System.out.println(range.inRange(LocalDateTime.of(2015, 11, 16, 15, 0))); // Mon Nov. 16 2015 at  3:00 PM

输出

false
true
false
false
true
true

<强>替代

当然,如果您使用DayOfWeek + LocalTime进行大量处理,则应考虑实施自己的LocalDayOfWeekTime类,将两者结合起来,方式相同{{1}只是一个合并的LocalDateTime + LocalDate(而且,请自行检查)。

答案 1 :(得分:1)

如果我们还假设间隔总是短于一周,那么问题就很明确了。

然后你可以模数1周工作;例如。如果你用毫秒表达所有内容,你可以模数N = 1000 * 60 * 60 * 24 * 7。

现在计算a = checkdate - start(mod N)和b = end - start(mod N)并测试a&lt;湾如果是这种情况,则日期在区间内。

你需要选择一个真实的开始和结束日期,在你的例子中是一个真正的星期五20:00和一个真正的星期六20:00。由于模运算而无关紧要。

还要记住,Java%运算符与负数的数学模型不同。因此,请确保仅将其应用于正数。

答案 2 :(得分:0)

首先,你需要让你的funktion采用datetime参数,如果在其中使用“now()”,你将无法测试它。

你的基本想法似乎很好,可以使用星期几作为数组的索引或检查范围,如果范围通过一周的开始/结束,则使其成为两个范围或反转它。

答案 3 :(得分:0)

我编写了一个测试程序,它需要两个日期时间(范围),然后测试一个日期时间,看看它是否属于该范围。

我使用了完整日期,如果你愿意,你可以跨越一周以上。

以下是测试结果:

Testing for the date range Fri, 13 Nov 2015 20:00 to Sun, 15 Nov 2015 20:00
12 Nov 2015 22:00: false
14 Nov 2015 08:00: true
16 Nov 2015 10:00: false

这是代码。我将日期时间输入为字符串,以便更容易使用此代码,

package com.ggl.testing;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateRangeTesting {

    private static final SimpleDateFormat inputDateFormat = new SimpleDateFormat(
            "d MMM yyyy H:mm");
    private static final SimpleDateFormat outputDateFormat = new SimpleDateFormat(
            "EEE, d MMM yyyy H:mm");

    private Calendar fromDate;
    private Calendar toDate;

    public static void main(String[] args) {
        DateRangeTesting drTesting = new DateRangeTesting("13 Nov 2015 20:00",
                "15 Nov 2015 20:00");
        printResult("12 Nov 2015 22:00", drTesting);
        printResult("14 Nov 2015 08:00", drTesting);
        printResult("16 Nov 2015 10:00", drTesting);
    }

    private static void printResult(String s, DateRangeTesting drTesting) {
        System.out.println(s + ": " + drTesting.testDate(s));
    }

    public DateRangeTesting(String fromDateString, String toDateString) {
        this.fromDate = convertInputDate(fromDateString);
        this.toDate = convertInputDate(toDateString);
        System.out.println(displayRange());
    }

    private String displayRange() {
        StringBuilder builder = new StringBuilder();
        builder.append("Testing for the date range ");
        builder.append(outputDateFormat.format(fromDate.getTime()));
        builder.append(" to ");
        builder.append(outputDateFormat.format(toDate.getTime()));

        return builder.toString();
    }

    public boolean testDate(String dateString) {
        Calendar testDate = convertInputDate(dateString);
        boolean fromTest = fromDate.compareTo(testDate) <= 0;
        boolean toTest = testDate.compareTo(toDate) <= 0;
        return fromTest && toTest;
    }

    private Calendar convertInputDate(String dateString) {
        Calendar calendar = Calendar.getInstance();
        try {
            Date tempDate = inputDateFormat.parse(dateString);
            calendar.setTime(tempDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return calendar;
    }

}