【问题标题】:How to check if the given time falls in mentioned time range如何检查给定时间是否在提到的时间范围内
【发布时间】:2020-01-29 09:17:19
【问题描述】:

我想检查我的日期值是否来自 -

Date d = convertCurrentTimeToSpecificTimeZone("America/Chicago", 2, 30);

在上午 10 点到下午 6 点之间。

我在 StackOverflow similar question 上找到了一些类似的链接,并使用了该线程中的一些代码。

我只想检查任何时区的当前时间是否在上午 10 点到下午 6 点之间。如果是,打印“是”,否则打印“否”。

目前为以下代码:

    String string1 = "10:11:13";
    Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(time1);
    calendar1.add(Calendar.DATE, 1);
    System.out.println(calendar1.getTime().toString());

它只打印 1970 年的上午 10:11 时间。像这样 - Fri Jan 02 10:11:13 IST 1970。

但我想检查今天或任何未来的日期时间是否在上午 10 点到下午 6 点之间。

以下是代码参考:

public static Date convertCurrentTimeToSpecificTimeZone(String timeZone, int increaseDateBy,
        int increaseMinutesBy) {
    Calendar calendar = Calendar.getInstance();
    TimeZone fromTimeZone = calendar.getTimeZone();
    TimeZone toTimeZone = TimeZone.getTimeZone(timeZone);
    calendar.setTimeZone(fromTimeZone);
    calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
    if (fromTimeZone.inDaylightTime(calendar.getTime())) {
        calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
    }
    calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
    if (toTimeZone.inDaylightTime(calendar.getTime())) {
        calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
    }
    increaseCalenderDateBy(calendar, increaseDateBy);
    increaseCalenderMinuteBy(calendar, increaseMinutesBy);
    return calendar.getTime();
}

public static void getTimeBetweenRange() throws ParseException {
    String string1 = "10:11:13";
    Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(time1);
    calendar1.add(Calendar.DATE, 1);
    System.out.println(calendar1.getTime().toString());

    String string2 = "18:49:00";
    Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(time2);
    calendar2.add(Calendar.DATE, 1);
    System.out.println(calendar2.getTime().toString());

    Date d = convertCurrentTimeToSpecificTimeZone("America/Chicago", 2, 30);
    Calendar calendar3 = Calendar.getInstance();
    calendar3.setTime(d);
    System.out.println(calendar3.getTime().toString());

    Date x = calendar3.getTime();
    if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
        // checkes whether the current time is between 14:49:00 and 20:11:13.
        System.out.println(true);
    } else
        System.out.println(false);
}

所以我下面代码的输出是:

Fri Jan 02 10:11:13 IST 1970
Fri Jan 02 18:49:00 IST 1970
Fri Jan 31 03:15:07 IST 2020

【问题讨论】:

  • 我建议你不要使用DateSimpleDateFormatCalendarTimeZone 中的任何一个类。它们都设计得很糟糕,而且已经过时了。而是使用ZonedDateTime、ZoneId` 和DateTimeFormatter,均来自java.time, the modern Java date and time API
  • 不清楚,抱歉。 10:11:13(开始和结束时间)应该在美国/芝加哥时区理解吗?还是您或用户自己的时区?还是……?
  • @Ole V.V. - 是的,10:11:13(开始和结束时间)以美国/芝加哥时区为准。

标签: java date time calendar range


【解决方案1】:

不是很清楚。对于这个答案,我假设您的所有时间都将在美国/芝加哥时区进行理解。如果这不是您想要的,请恢复。

java.time

    ZoneId zone = ZoneId.of("America/Chicago");

    ZonedDateTime zdt = ZonedDateTime.now(zone).plusDays(2).plusMinutes(30);

    LocalTime rangeStart = LocalTime.parse("10:11:13");
    LocalTime rangeEnd = LocalTime.parse("18:49:00");

    LocalTime time = zdt.toLocalTime();
    if (!time.isBefore(rangeStart) && time.isBefore(rangeEnd)) {
        System.out.println("Yes");
    } else {
        System.out.println("No");
    }

当我刚才(芝加哥时间 11:30)运行这段代码 sn-p 时,输出是:

是的

我正在使用 java.time,这是现代 Java 日期和时间 API,并建议您也这样做。它比旧的、过时的和设计不佳的类 DateSimpleDateFormatCalendarTimeZone 更好用。

LocalTime 是一天中从 00:00(含)到 24:00(不含)的时间。通过比较 LocalTimeobjects,我们忽略了日期,并且在 1970 年或历史上的其他时间不相关的日期没有问题。

编辑:

还有可能获取 rangeStart 的日期和时间和 rangeEnd 以验证我们在哪个特定日期和时间 检查条件?

不,那没有意义。由于LocalTime 是一天中的时间没有日期,因此无法从中获取日期。但是您可以打印ZonedDateTime 并验证其日期部分。为了确保代码正确,请编写一些单元测试。

链接: Oracle tutorial: Date Time 解释如何使用 java.time。

【讨论】:

  • 是的,所有时间都应该在美国/芝加哥时区。但是,如果需要,可以更改时区。让我试试你的代码,如果它满足要求会让你知道。谢谢朋友。
  • 太好了,听起来我运气不错。您可以在第一行代码中更改时区以使用不同的时区。
  • 感谢 Ole V.V.!我想它按预期工作。是否可以获取 rangeStart 和 rangeEnd 的日期和时间,以验证我们正在检查条件的特定日期和时间?
  • 不,你不能,看我的编辑。你需要相信它是正确的。 :-)
【解决方案2】:

一种简单的方法可能是将您的时间 Strings 解析为 LocalTime 的实例并进行比较。您必须决定是否包含开始时间和结束时间...

支持某些格式,因为您可能必须通过 Strings 或不带 AM/PM:

public static boolean isInTimeSlot(String time, String timeSlotStart, String timeSlotEnd) {
    // create a formatter that supports different formats for the String arguments
    DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("[hh:mm:ss a][HH:mm:ss][h a]");
    // parse each argument to a LocalTime
    LocalTime timeOfDay = LocalTime.parse(time, parserDtf);
    LocalTime fromTime = LocalTime.parse(timeSlotStart, parserDtf);
    LocalTime toTime = LocalTime.parse(timeSlotEnd, parserDtf);
    // and return if the given time is in the time slot (including start and end time)
    return timeOfDay.equals(fromTime) || timeOfDay.equals(toTime)
            || (timeOfDay.isAfter(fromTime) && timeOfDay.isBefore(toTime));
}

如果你像这样在main 中运行它

public static void main(String[] args) {
    // provide some sample times
    String[] times = { "10:31:17", "09:59:59", "6 PM", "4 AM", "06:00:01 PM" };
    // provide a time slot
    String from = "10 AM";
    String to = "6 PM";

    // check the method for each time string
    for (String time : times) {
        if (isInTimeSlot(time, from, to)) {
            System.out.println(time + " is in the time slot at or between "
                                + from + " and " + to);
        } else {
            System.err.println(time + " is not in the time slot at or between " 
                                + from + " and " + to);
        }
    }
}

输出将是

10:31:17 is in the time slot at or between 10 AM and 6 PM
09:59:59 is not in the time slot at or between 10 AM and 6 PM
6 PM is in the time slot at or between 10 AM and 6 PM
4 AM is not in the time slot at or between 10 AM and 6 PM
06:00:01 PM is not in the time slot at or between 10 AM and 6 PM

【讨论】:

  • 当你传递这样的时间时: String[] times = { "10:31:17", "09:59:59", "6 PM", "4 AM", "06 :00:01 PM"}; Java 将 10:31:17 视为默认日期 -1 Jan 1970 的时间,其他时间相同。但我需要基于时区的时间安排并作为今天日期的参考。
  • 是的,此解决方案本身不处理区域,但您可以轻松扩展该方法以采用 ZoneIdZoneOffset 并使用 ZonedDateTimeOffsetDateTime。查看@OleV.V. 给出的答案。
【解决方案3】:

我只想检查任何时区的当前时间是否在上午 10 点到下午 6 点之间。如果是,打印“是”,否则打印“否”。

为此,以下代码将完成这项工作。

LocalTime lt = LocalTime.now();
if( lt.isAfter( LocalTime.of( 10, 0 ) ) && lt.isBefore( LocalTime.of( 18, 0 ) ) ) System.out.println( "Yes" );
else System.out.println( "No" );

由于您有Date 实例,您可以将它们转换为LocalTime 实例,如下所示并使用相同的比较机制。

Date d = new Date(); //Change this to your way of creating the Date instance
LocalTime lt = LocalDateTime.ofEpochSecond( d.getTime(), 0, ZoneOffset.ofHours( 0 ) ).toLocalTime();

希望这会有所帮助。

【讨论】:

  • 谢谢@Sree Kumar。但是当我运行这行代码时: LocalTime lt = LocalDateTime.ofEpochSecond(d.getTime(), 0, null ).toLocalTime();它给了我空指针异常。
  • @kalpesh 对不起,我的错误。我现在已经编辑了代码。你可以检查吗?我已经包含了默认的 ZoneOffset 0,而不是 null
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 2018-04-07
  • 2021-05-09
  • 2016-10-23
相关资源
最近更新 更多