无论日期如何,检查给定时间是否介于两次之间

时间:2021-06-15 21:29:43

I have timespans:

我有时间跨度:

String time1 = 01:00:00

String time1 = 01:00:00

String time2 = 05:00:00

String time2 = 05:00:00

I want to check if time1 and time2 both lies between 20:11:13 and 14:49:00.

我想检查time1和time2是否介于20:11:13和14:49:00之间。

Actually, 01:00:00 is greater than 20:11:13 and less than 14:49:00 considering 20:11:13 is always less than 14:49:00. This is given prerequisite.

实际上,01:00:00大于20:11:13且小于14:49:00,考虑到20:11:13总是小于14:49:00。这是先决条件。

So what I want is, 20:11:13 < 01:00:00 < 14:49:00.

所以我想要的是,20:11:13 <01:00:00 <14:49:00。

So I need something like that:

所以我需要这样的东西:

 public void getTimeSpans()
{
    boolean firstTime = false, secondTime = false;

    if(time1 > "20:11:13" && time1 < "14:49:00")
    {
       firstTime = true;
    }

    if(time2 > "20:11:13" && time2 < "14:49:00")
    {
       secondTime = true;
    }
 }

I know that this code does not give correct result as I am comparing the string objects.

我知道这个代码没有给出正确的结果,因为我正在比较字符串对象。

How to do that as they are the timespans but not the strings to compare?

怎么做,因为他们是时间跨度而不是比较的字符串?

19 个解决方案

#1


37  

You can use the Calendar class in order to check.

您可以使用Calendar类进行检查。

For example:

try {
    String string1 = "20:11:13";
    Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(time1);

    String string2 = "14:49:00";
    Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(time2);
    calendar2.add(Calendar.DATE, 1);

    String someRandomTime = "01:00:00";
    Date d = new SimpleDateFormat("HH:mm:ss").parse(someRandomTime);
    Calendar calendar3 = Calendar.getInstance();
    calendar3.setTime(d);
    calendar3.add(Calendar.DATE, 1);

    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);
    }
} catch (ParseException e) {
    e.printStackTrace();
}

#2


16  

tl;dr

20:11:13 < 01:00:00 < 14:49:00

20:11:13 <01:00:00 <14:49:00

LocalTime target = LocalTime.parse( "01:00:00" ) ;
Boolean targetInZone = ( 
    target.isAfter( LocalTime.parse( "20:11:13" ) ) 
    && 
    target.isBefore( LocalTime.parse( "14:49:00" ) ) 
) ; 

java.time.LocalTime

The java.time classes include LocalTime to represent a time-of-day only without a date and without a time zone.

java.time类包括LocalTime,仅表示没有日期且没有时区的时间。

So what I want is, 20:11:13 < 01:00:00 < 14:49:00.

所以我想要的是,20:11:13 <01:00:00 <14:49:00。

First we define the boundaries. Your input strings happen to comply with standard ISO 8601 formats. The java.time classes use ISO 8601 formats by default, so no need to specify a formatting pattern.

首先,我们定义边界。您的输入字符串恰好符合标准ISO 8601格式。默认情况下,java.time类使用ISO 8601格式,因此无需指定格式设置模式。

LocalTime start = LocalTime.parse( "20:11:13" );
LocalTime stop = LocalTime.parse( "14:49:00" );

And define our test case, the target 01:00:00.

并定义我们的测试用例,目标为01:00:00。

LocalTime target = LocalTime.parse( "01:00:00" );

Now we are set up to compare these LocalTime objects. We want to see if the target is after the later time but before the earlier time. That means middle of the night in this case, between approximately 8 PM and 3 AM the next morning.

现在我们设置比较这些LocalTime对象。我们想看看目标是在较晚时间之后但在较早时间之前。这意味着在这种情况下半夜,第二天早上大约晚上8点到凌晨3点之间。

Boolean isTargetAfterStartAndBeforeStop = ( target.isAfter( start ) && target.isBefore( stop ) ) ;

That test can be more simply stated as “not between 3 AM and 8 PM”. We could then generalize to any pair of LocalTime objects where we test for between if the start comes before the stop with a 24-hour clock, and not between if start comes after the stop (as in the case of this Question).

该测试可以更简单地说“不在凌晨3点到晚上8点之间”。然后我们可以推广到任何一对LocalTime对象,我们在这两个对象之间进行测试,如果开始是在24小时制停止之前,而不是在停止之后是否开始(如本问题的情况)。

Further more, spans of time are usually handled with the Half-Open approach where the beginning is inclusive while the ending is exclusive. So a "between" comparison, strictly speaking, would be “is the target equal to or later than start AND the target is before stop”, or more simply, “is target not before start AND before stop”.

此外,时间跨度通常采用半开放式方法处理,其中开头是包容性的,而结尾是独占的。因此,严格地说,“之间”比较将是“目标等于或晚于开始并且目标是在停止之前”,或者更简单地说,“目标不是在开始之前和停止之前”。

Boolean isBetweenStartAndStopStrictlySpeaking = 
    ( ( ! target.isBefore( start ) && target.isBefore( stop ) ) ;

If the start is after the stop, within a 24-hour clock, then assume we want the logic suggested in the Question (is after 8 PM but before 3 AM).

如果开始是在停止之后,在24小时内,则假设我们想要问题中建议的逻辑(在晚上8点之后但在凌晨3点之前)。

if( start.isAfter( stop ) ) {
    return ! isBetweenStartAndStopStrictlySpeaking ;
} else {
    return isBetweenStartAndStopStrictlySpeaking ;
}

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧遗留日期时间类,如java.util.Date,Calendar和SimpleDateFormat。

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

现在处于维护模式的Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle教程。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310。

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

您可以直接与数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC驱动程序。不需要字符串,不需要java.sql。*类。

Where to obtain the java.time classes?

从哪里获取java.time类?

  • Java SE 8, Java SE 9, Java SE 10, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • 带有捆绑实现的标准Java API的一部分。

    • Java 9 adds some minor features and fixes.
    • Java 9增加了一些小功能和修复。

  • Java SE 8,Java SE 9,Java SE 10和更高版本内置。带有捆绑实现的标准Java API的一部分。 Java 9增加了一些小功能和修复。

  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • 许多java.time功能都被反向移植到ThreeTen-Backport中的Java 6和7。

  • Java SE 6和Java SE 7许多java.time功能都被反向移植到ThreeTen-Backport中的Java 6和7。

  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • 更高版本的Android捆绑java.time类的实现。

    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
    • 对于早期的Android(<26),ThreeTenABP项目采用ThreeTen-Backport(如上所述)。请参见如何使用ThreeTenABP ....

  • Android更新版本的Android捆绑java.time类的实现。对于早期的Android(<26),ThreeTenABP项目采用ThreeTen-Backport(如上所述)。请参见如何使用ThreeTenABP ....

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-Extra项目使用其他类扩展了java.time。该项目是未来可能添加到java.time的试验场。您可以在这里找到一些有用的课程,如Interval,YearWeek,YearQuarter等。

#3


16  

The answer given by @kocko works in only same day.
If start time "23:00:00" and end "02:00:00"[next day] and current time is "01:30:00" then result will false...
I modified the @kocko's answer to work perfectly

@kocko给出的答案仅在同一天起作用。如果开始时间“23:00:00”并且结束“02:00:00”[第二天]并且当前时间是“01:30:00”那么结果将是假的...我修改了@ kocko的答案以完美地工作

public static boolean isTimeBetweenTwoTime(String initialTime, String finalTime, 
    String currentTime) throws ParseException {

    String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
    if (initialTime.matches(reg) && finalTime.matches(reg) && 
        currentTime.matches(reg)) 
    {
        boolean valid = false;
        //Start Time
        //all times are from java.util.Date
        Date inTime = new SimpleDateFormat("HH:mm:ss").parse(initialTime);
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(inTime);

        //Current Time
        Date checkTime = new SimpleDateFormat("HH:mm:ss").parse(currentTime);
        Calendar calendar3 = Calendar.getInstance();
        calendar3.setTime(checkTime);

        //End Time
        Date finTime = new SimpleDateFormat("HH:mm:ss").parse(finalTime);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(finTime);

        if (finalTime.compareTo(initialTime) < 0) 
        {
            calendar2.add(Calendar.DATE, 1);
            calendar3.add(Calendar.DATE, 1);
        }

        java.util.Date actualTime = calendar3.getTime();
        if ((actualTime.after(calendar1.getTime()) || 
             actualTime.compareTo(calendar1.getTime()) == 0) && 
             actualTime.before(calendar2.getTime())) 
        {
            valid = true;
            return valid;
        } else {
            throw new IllegalArgumentException("Not a valid time, expecting 
            HH:MM:SS format");
        }
    }
}

Output

"07:00:00" - "17:30:00" - "15:30:00" [current] - true
"17:00:00" - "21:30:00" - "16:30:00" [current] - false
"23:00:00" - "04:00:00" - "02:00:00" [current] - true
"00:30:00" - "06:00:00" - "06:00:00" [current] - false 

(I have included lower limit value to [upper limit value-1])

(我已将下限值包含在[上限值-1]中)

#4


13  

Modified @Surendra Jnawali' code. It fails

修改了@Surendra Jnawali'代码。它失败

if current time is 23:40:00 i.e greater than start time and less than equals to 23:59:59.

如果当前时间是23:40:00,即大于开始时间且小于等于23:59:59。

All credit goes to the real owner

所有信用都归于真正的所有者

This is how it should be :This works perfect

这应该是这样的:这很完美

public static boolean isTimeBetweenTwoTime(String argStartTime,
            String argEndTime, String argCurrentTime) throws ParseException {
        String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
        //
        if (argStartTime.matches(reg) && argEndTime.matches(reg)
                && argCurrentTime.matches(reg)) {
            boolean valid = false;
            // Start Time
            java.util.Date startTime = new SimpleDateFormat("HH:mm:ss")
                    .parse(argStartTime);
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startTime);

            // Current Time
            java.util.Date currentTime = new SimpleDateFormat("HH:mm:ss")
                    .parse(argCurrentTime);
            Calendar currentCalendar = Calendar.getInstance();
            currentCalendar.setTime(currentTime);

            // End Time
            java.util.Date endTime = new SimpleDateFormat("HH:mm:ss")
                    .parse(argEndTime);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endTime);

            //
            if (currentTime.compareTo(endTime) < 0) {

                currentCalendar.add(Calendar.DATE, 1);
                currentTime = currentCalendar.getTime();

            }

            if (startTime.compareTo(endTime) < 0) {

                startCalendar.add(Calendar.DATE, 1);
                startTime = startCalendar.getTime();

            }
            //
            if (currentTime.before(startTime)) {

                System.out.println(" Time is Lesser ");

                valid = false;
            } else {

                if (currentTime.after(endTime)) {
                    endCalendar.add(Calendar.DATE, 1);
                    endTime = endCalendar.getTime();

                }

                System.out.println("Comparing , Start Time /n " + startTime);
                System.out.println("Comparing , End Time /n " + endTime);
                System.out
                        .println("Comparing , Current Time /n " + currentTime);

                if (currentTime.before(endTime)) {
                    System.out.println("RESULT, Time lies b/w");
                    valid = true;
                } else {
                    valid = false;
                    System.out.println("RESULT, Time does not lies b/w");
                }

            }
            return valid;

        } else {
            throw new IllegalArgumentException(
                    "Not a valid time, expecting HH:MM:SS format");
        }

    }

RESULT

Comparing , Start Time /n    Thu Jan 01 23:00:00 IST 1970
Comparing , End Time /n      Fri Jan 02 02:00:00 IST 1970
Comparing , Current Time /n  Fri Jan 02 01:50:00 IST 1970
RESULT, Time lies b/w

#5


7  

 Calendar now = Calendar.getInstance();

 int hour = now.get(Calendar.HOUR_OF_DAY); // Get hour in 24 hour format
 int minute = now.get(Calendar.MINUTE);

 Date date = parseDate(hour + ":" + minute);
 Date dateCompareOne = parseDate("08:00");
 Date dateCompareTwo = parseDate("20:00");

 if (dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
    //your logic
 }

 private Date parseDate(String date) {

    final String inputFormat = "HH:mm";
    SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
    try {
         return inputParser.parse(date);
    } catch (java.text.ParseException e) {
         return new Date(0);
    }
 }

Further more, to be more precise, If you compare a time between an interval more than 00:00 to 24:00 of that day, you need to parse the day too.

此外,更准确地说,如果您比较当天00:00到24:00之间的时间间隔,您还需要解析当天。

#6


2  

Sounds to me that your problem is an OR situation... You want to check if time1 > 20:11:13 OR time1 < 14:49:00.

听我说你的问题是OR情况......你想检查时间1> 20:11:13或时间1 <14:49:00。

There will never be a time greater to 20:11:13 that exceeds your range through the other end (14:49:00) and viceversa. Think of it as if you are checking that a time is NOT between a properly ordered couple of timestamps.

永远不会有超过20:11:13的时间超过你的范围到另一端(14:49:00),反之亦然。可以把它想象成你正在检查时间是否在正确排序的时间戳之间。

#7


2  

Following method checks whether 'validateTime' is between 'startTime' & 'endTime' or not while considering possibility that 'endTime' can be a next day. To use it properly parse your dates in "HH:mm" formant.

以下方法检查'validateTime'是否介于'startTime'和'endTime'之间,同时考虑'endTime'可能是第二天的可能性。要使用它,请在“HH:mm”共振峰中正确解析日期。

 public static final boolean isBetweenValidTime(Date startTime, Date endTime, Date validateTime)
 {
        boolean validTimeFlag = false;

        if(endTime.compareTo(startTime) <= 0)
        {
            if(validateTime.compareTo(endTime) < 0 || validateTime.compareTo(startTime) >= 0)
            {
                 validTimeFlag = true;
            }
        }
        else if(validateTime.compareTo(endTime) < 0 && validateTime.compareTo(startTime) >= 0)
        {
             validTimeFlag = true;  
        }

        return validTimeFlag;
 }

#8


2  

After reading a few replies, I feel the writing is too complicated. Try my code

看了几篇回复后,我觉得写作太复杂了。试试我的代码

 public static boolean compare(String system_time, String currentTime, String endtimes) {
    try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");

        Date startime = simpleDateFormat.parse("19:25:00");
        Date endtime = simpleDateFormat.parse("20:30:00");

        //current time
        Date current_time = simpleDateFormat.parse("20:00:00");

    if (current_time.after(startime) && current_time.before(endtime)) {
            System.out.println("Yes");
            return true;
      }
    else if (current_time.after(startime) && current_time.after(endtime)) {
         return true; //overlap condition check
      }
     else {
            System.out.println("No");
            return false;
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return false;
 } 

#9


1  

As with the help of @kocko, the complete working code is as below:

在@kocko的帮助下,完整的工作代码如下:

try{
Date time11 = new SimpleDateFormat("HH:mm:ss").parse("20:11:13");
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time11);

Date time22 = new SimpleDateFormat("HH:mm:ss").parse("14:49:00");
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time22);

Date currentTime = new SimpleDateFormat("HH:mm:ss").parse("00:00:00");
Calendar startingCalendar = Calendar.getInstance();
startingCalendar.setTime(currentTime);
startingCalendar.add(Calendar.DATE, 1);



//let's say we have to check about 01:00:00
String someRandomTime = time1;
Date d = new SimpleDateFormat("HH:mm:ss").parse(someRandomTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);

if(startingCalendar.getTime().after(calendar1.getTime()))
{
calendar2.add(Calendar.DATE, 1);

    calendar3.add(Calendar.DATE, 1);
}

Date x = calendar3.getTime();

if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) 
{
System.out.println("Time is in between..");
}
else
{
System.out.println("Time is not in between..");
}

} catch (ParseException e) 
{
e.printStackTrace();
}

#10


1  

strip colons from the $time, $to and $from strings, convert to int and then use the following condition to check if the time is between from and to. Example is in php, but shouldn't matter.

从$ time中剥离冒号,从字符串中取$和$,转换为int,然后使用以下条件检查时间是否在from和to之间。示例是在php中,但不应该重要。

if(($to < $from && ($time >= $from || $time <= $to)) ||
    ($time >= $from && $time <= $to)) {
    return true;
}

#11


1  

The Actual working function will be as follows

实际工作功能如下

public static boolean isTimeBetweenTwoTime(Date startTime, Date stopTime, Date currentTime) {
    //Start Time
    Calendar StartTime = Calendar.getInstance();
    StartTime.setTime(startTime);
    //Current Time
    Calendar CurrentTime = Calendar.getInstance();
    CurrentTime.setTime(currentTime);
    //Stop Time
    Calendar StopTime = Calendar.getInstance();
    StopTime.setTime(stopTime);

    if (stopTime.compareTo(startTime) < 0) {
        if (CurrentTime.compareTo(StopTime) < 0) {
            CurrentTime.add(Calendar.DATE, 1);
        }
        StopTime.add(Calendar.DATE, 1);
    }
    return CurrentTime.compareTo(StartTime) >= 0 && CurrentTime.compareTo(StopTime) < 0;
}

#12


1  

In your case the starting time (20:11:13) is larger than the ending time (14:49:00). It is a reasonable assumption that you could solve the problem by adding a day on the ending time or subtracting a day from the starting time. if you do so, you will be trapped because you do not know on which day the testing time is.

在您的情况下,开始时间(20:11:13)大于结束时间(14:49:00)。可以合理地假设您可以通过在结束时间添加一天或从开始时间减去一天来解决问题。如果你这样做,你将被困,因为你不知道测试时间是哪一天。

You can avoid this trap by checking whether your testing time is between the ending time and starting time. If true, then result is "not in between"; else result is "well in between".

您可以通过检查测试时间是否在结束时间和开始时间之间来避免此陷阱。如果是,那么结果是“不介于”之间;否则结果是“介于两者之间”。

Here is the function in JAVA I have been using. It works so far for me. Good luck.

这是我一直在使用的JAVA中的功能。它对我来说到目前为止。祝你好运。

boolean IsTimeInBetween(Calendar startC, Calendar endC, Calendar testC){
    // assume year, month and day of month are all equal.
    startC.set(1,1,1);
    endC.set(1,1,1);
    testC.set(1,1,1);

    if (endC.compareTo(startC) > 0) {
        if ((testC.compareTo(startC)>=0) && (testC.compareTo(endC)<=0)) {
            return true;
        }else {
            return false;
        }
    }else if  (endC.compareTo(startC) < 0) {
        if ((testC.compareTo(endC) >= 0) && (testC.compareTo(startC) <= 0)) {
            return false;
        } else {
            return true;
        }
    } else{ // when endC.compareTo(startC)==0, I return a ture value. Change it if you have different application. 
        return true;
    }
}

To create a Calender instance you can use:

要创建日历实例,您可以使用:

Calendar startC = Calendar.getInstance();
startC.set(Calendar.HOUR_OF_DAY, 20);
startC.set(Calendar.MINUTE,11);
startC.set(Calendar.SECOND,13);

#13


1  

Java 8 - LocalDateTime

Java 8 - LocalDateTime

What about this?

那这个呢?

final LocalDateTime now = LocalDateTime.now();
final LocalDateTime minRange = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 22, 30); //Today, 10:30pm
LocalDateTime maxRange = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 6, 30); //Tomorrow, 6:30am
maxRange = maxRange.plusDays(1); //Ensures that you don't run into an exception if minRange is the last day in the month.
if (now.isAfter(minRange) && now.isBefore(maxRange)) {
    //Action
}

#14


1  

Using LocalTime would simply ignore the Date value:

使用LocalTime只会忽略Date值:

public class TimeIntervalChecker {

static final LocalTime time1 = LocalTime.parse( "20:11:13"  ) ;
static final LocalTime time2 = LocalTime.parse( "14:49:00" ) ;

    public static void main(String[] args) throws java.lang.Exception {

        LocalTime nowUtcTime = LocalTime.now(Clock.systemUTC());

        if (nowUtcTime.isAfter(time1) && nowUtcTime.isBefore(time2)){
              System.out.println(nowUtcTime+" is after: "+ time1+" and before: "+ time2);
        } 

}

#15


1  

In the code snipet below, it is being verified that if the current time (can be any) exists between start and end time or not:

在下面的代码snipet中,正在验证如果当前时间(可以是任何时间)存在于开始和结束时间之间:

        Calendar startTimeCal = Calendar.getInstance();
        startTimeCal.setTime(startTime);

        int startTimeHour = startTimeCal.get(Calendar.HOUR_OF_DAY);

        if (startTimeHour == 0){
            startTimeHour = 24;
        }

        int startTimeMinutes = startTimeCal.get(Calendar.MINUTE);

        Calendar curTimeCal = Calendar.getInstance();
        curTimeCal.setTime(currentTime);

        int curTimeHour = curTimeCal.get(Calendar.HOUR_OF_DAY);
        int curTimeMinutes = curTimeCal.get(Calendar.MINUTE);

        Calendar endTimeCal = Calendar.getInstance();
        endTimeCal.setTime(endTime);

        int endTimeHour = endTimeCal.get(Calendar.HOUR_OF_DAY);

        if (endTimeHour == 0) {
            endTimeHour = 24;
        }

        int endTimeMinutes = endTimeCal.get(Calendar.MINUTE);

        if (((curTimeHour > startTimeHour) || (curTimeHour == startTimeHour && curTimeMinutes >= startTimeMinutes)) &&
                ((curTimeHour < endTimeHour) || (curTimeHour == endTimeHour && curTimeMinutes <= endTimeHour))) {
          //time exists between start and end time
        } else {
              //time doesn't exist between start and end time
        }

#16


1  

sorry for the sudo code..I'm on a phone. ;)

对不起sudo代码..我在打电话。 ;)

between = (time < string2 && time > string1);
if (string1 > string2)  between = !between;

if they are timestamps or strings this works. just change the variable names to match

如果它们是时间戳或字符串,这是有效的。只需更改变量名称即可

#17


0  

Logically if you do the following you should always be ok granted we use military time...

从逻辑上讲,如果您执行以下操作,您应该总是可以使用军事时间...

if start time is greater than end time add 24 to end time else use times as is

如果开始时间大于结束时间,则将24添加到结束时间,否则使用时间

compare current time to be inbetween start and end time.

比较当前时间在开始和结束时间之间。

#18


0  

As many people noticed, it's not a date problem, it's a logic problem. Let's assume a day is splitted in two intervals: one lies between 20:11:13 and 14:49:00, while the other lies between 14:49:00 and 20:11:13 (which interval the extremes belong is up to you). If you want to check if a certain time is included in the 20:11:13/14:49:00 one, the one you're interested of, just check if it's included in the other one, 14:49:00/20:11:13, which is much easier because the natural order of the numbers, and then negate the result.

正如许多人注意到的那样,这不是日期问题,而是一个逻辑问题。让我们假设一天分为两个区间:一个位于20:11:13到14:49:00之间,而另一个位于14:49:00到20:11:13之间(极端所属的区间是您)。如果您想检查20:11:13/14:49:00中是否包含一个您感兴趣的时间,请检查它是否包含在另一个中,14:49:00 / 20:11:13,这更容易因为数字的自然顺序,然后否定结果。

#19


-2  

This is working, but needs some improvement.

这是有效的,但需要一些改进。

long timeToSeconds(String time){
    long ret=0;
    String[] ar = time.split("\\:");
    for(int i=0;i < ar.length ; i++){
        ret+= Long.valueOf(ar[i])* Math.pow(60,(2-i)); // (60^(2-i));
    }
    return ret;
}
boolean isTimeBetween(String startTime, String endTime,String currentTime) {
    long lCurrentTime = timeToSeconds(currentTime);
    long lstartTime = timeToSeconds(startTime);
    long lEndTime = timeToSeconds(endTime);

    if(((lstartTime-lCurrentTime)*(lEndTime-lCurrentTime)*(lstartTime-lEndTime))>0){
        return true;
    }else{
        return false;
    }
}

Modify your code like this-

像这样修改你的代码 -

 public void getTimeSpans(){
    boolean firstTime = false, secondTime = false;

    if(isTimeBetween("20:11:13" ,"14:49:00",time1)
    {
        firstTime = true;
    }

    if(isTimeBetween("20:11:13" ,"14:49:00",time2)
    {
        secondTime = true;
    }
}

#1


37  

You can use the Calendar class in order to check.

您可以使用Calendar类进行检查。

For example:

try {
    String string1 = "20:11:13";
    Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(time1);

    String string2 = "14:49:00";
    Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(time2);
    calendar2.add(Calendar.DATE, 1);

    String someRandomTime = "01:00:00";
    Date d = new SimpleDateFormat("HH:mm:ss").parse(someRandomTime);
    Calendar calendar3 = Calendar.getInstance();
    calendar3.setTime(d);
    calendar3.add(Calendar.DATE, 1);

    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);
    }
} catch (ParseException e) {
    e.printStackTrace();
}

#2


16  

tl;dr

20:11:13 < 01:00:00 < 14:49:00

20:11:13 <01:00:00 <14:49:00

LocalTime target = LocalTime.parse( "01:00:00" ) ;
Boolean targetInZone = ( 
    target.isAfter( LocalTime.parse( "20:11:13" ) ) 
    && 
    target.isBefore( LocalTime.parse( "14:49:00" ) ) 
) ; 

java.time.LocalTime

The java.time classes include LocalTime to represent a time-of-day only without a date and without a time zone.

java.time类包括LocalTime,仅表示没有日期且没有时区的时间。

So what I want is, 20:11:13 < 01:00:00 < 14:49:00.

所以我想要的是,20:11:13 <01:00:00 <14:49:00。

First we define the boundaries. Your input strings happen to comply with standard ISO 8601 formats. The java.time classes use ISO 8601 formats by default, so no need to specify a formatting pattern.

首先,我们定义边界。您的输入字符串恰好符合标准ISO 8601格式。默认情况下,java.time类使用ISO 8601格式,因此无需指定格式设置模式。

LocalTime start = LocalTime.parse( "20:11:13" );
LocalTime stop = LocalTime.parse( "14:49:00" );

And define our test case, the target 01:00:00.

并定义我们的测试用例,目标为01:00:00。

LocalTime target = LocalTime.parse( "01:00:00" );

Now we are set up to compare these LocalTime objects. We want to see if the target is after the later time but before the earlier time. That means middle of the night in this case, between approximately 8 PM and 3 AM the next morning.

现在我们设置比较这些LocalTime对象。我们想看看目标是在较晚时间之后但在较早时间之前。这意味着在这种情况下半夜,第二天早上大约晚上8点到凌晨3点之间。

Boolean isTargetAfterStartAndBeforeStop = ( target.isAfter( start ) && target.isBefore( stop ) ) ;

That test can be more simply stated as “not between 3 AM and 8 PM”. We could then generalize to any pair of LocalTime objects where we test for between if the start comes before the stop with a 24-hour clock, and not between if start comes after the stop (as in the case of this Question).

该测试可以更简单地说“不在凌晨3点到晚上8点之间”。然后我们可以推广到任何一对LocalTime对象,我们在这两个对象之间进行测试,如果开始是在24小时制停止之前,而不是在停止之后是否开始(如本问题的情况)。

Further more, spans of time are usually handled with the Half-Open approach where the beginning is inclusive while the ending is exclusive. So a "between" comparison, strictly speaking, would be “is the target equal to or later than start AND the target is before stop”, or more simply, “is target not before start AND before stop”.

此外,时间跨度通常采用半开放式方法处理,其中开头是包容性的,而结尾是独占的。因此,严格地说,“之间”比较将是“目标等于或晚于开始并且目标是在停止之前”,或者更简单地说,“目标不是在开始之前和停止之前”。

Boolean isBetweenStartAndStopStrictlySpeaking = 
    ( ( ! target.isBefore( start ) && target.isBefore( stop ) ) ;

If the start is after the stop, within a 24-hour clock, then assume we want the logic suggested in the Question (is after 8 PM but before 3 AM).

如果开始是在停止之后,在24小时内,则假设我们想要问题中建议的逻辑(在晚上8点之后但在凌晨3点之前)。

if( start.isAfter( stop ) ) {
    return ! isBetweenStartAndStopStrictlySpeaking ;
} else {
    return isBetweenStartAndStopStrictlySpeaking ;
}

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧遗留日期时间类,如java.util.Date,Calendar和SimpleDateFormat。

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

现在处于维护模式的Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle教程。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310。

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

您可以直接与数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC驱动程序。不需要字符串,不需要java.sql。*类。

Where to obtain the java.time classes?

从哪里获取java.time类?

  • Java SE 8, Java SE 9, Java SE 10, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • 带有捆绑实现的标准Java API的一部分。

    • Java 9 adds some minor features and fixes.
    • Java 9增加了一些小功能和修复。

  • Java SE 8,Java SE 9,Java SE 10和更高版本内置。带有捆绑实现的标准Java API的一部分。 Java 9增加了一些小功能和修复。

  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • 许多java.time功能都被反向移植到ThreeTen-Backport中的Java 6和7。

  • Java SE 6和Java SE 7许多java.time功能都被反向移植到ThreeTen-Backport中的Java 6和7。

  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • 更高版本的Android捆绑java.time类的实现。

    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
    • 对于早期的Android(<26),ThreeTenABP项目采用ThreeTen-Backport(如上所述)。请参见如何使用ThreeTenABP ....

  • Android更新版本的Android捆绑java.time类的实现。对于早期的Android(<26),ThreeTenABP项目采用ThreeTen-Backport(如上所述)。请参见如何使用ThreeTenABP ....

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-Extra项目使用其他类扩展了java.time。该项目是未来可能添加到java.time的试验场。您可以在这里找到一些有用的课程,如Interval,YearWeek,YearQuarter等。

#3


16  

The answer given by @kocko works in only same day.
If start time "23:00:00" and end "02:00:00"[next day] and current time is "01:30:00" then result will false...
I modified the @kocko's answer to work perfectly

@kocko给出的答案仅在同一天起作用。如果开始时间“23:00:00”并且结束“02:00:00”[第二天]并且当前时间是“01:30:00”那么结果将是假的...我修改了@ kocko的答案以完美地工作

public static boolean isTimeBetweenTwoTime(String initialTime, String finalTime, 
    String currentTime) throws ParseException {

    String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
    if (initialTime.matches(reg) && finalTime.matches(reg) && 
        currentTime.matches(reg)) 
    {
        boolean valid = false;
        //Start Time
        //all times are from java.util.Date
        Date inTime = new SimpleDateFormat("HH:mm:ss").parse(initialTime);
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(inTime);

        //Current Time
        Date checkTime = new SimpleDateFormat("HH:mm:ss").parse(currentTime);
        Calendar calendar3 = Calendar.getInstance();
        calendar3.setTime(checkTime);

        //End Time
        Date finTime = new SimpleDateFormat("HH:mm:ss").parse(finalTime);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(finTime);

        if (finalTime.compareTo(initialTime) < 0) 
        {
            calendar2.add(Calendar.DATE, 1);
            calendar3.add(Calendar.DATE, 1);
        }

        java.util.Date actualTime = calendar3.getTime();
        if ((actualTime.after(calendar1.getTime()) || 
             actualTime.compareTo(calendar1.getTime()) == 0) && 
             actualTime.before(calendar2.getTime())) 
        {
            valid = true;
            return valid;
        } else {
            throw new IllegalArgumentException("Not a valid time, expecting 
            HH:MM:SS format");
        }
    }
}

Output

"07:00:00" - "17:30:00" - "15:30:00" [current] - true
"17:00:00" - "21:30:00" - "16:30:00" [current] - false
"23:00:00" - "04:00:00" - "02:00:00" [current] - true
"00:30:00" - "06:00:00" - "06:00:00" [current] - false 

(I have included lower limit value to [upper limit value-1])

(我已将下限值包含在[上限值-1]中)

#4


13  

Modified @Surendra Jnawali' code. It fails

修改了@Surendra Jnawali'代码。它失败

if current time is 23:40:00 i.e greater than start time and less than equals to 23:59:59.

如果当前时间是23:40:00,即大于开始时间且小于等于23:59:59。

All credit goes to the real owner

所有信用都归于真正的所有者

This is how it should be :This works perfect

这应该是这样的:这很完美

public static boolean isTimeBetweenTwoTime(String argStartTime,
            String argEndTime, String argCurrentTime) throws ParseException {
        String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
        //
        if (argStartTime.matches(reg) && argEndTime.matches(reg)
                && argCurrentTime.matches(reg)) {
            boolean valid = false;
            // Start Time
            java.util.Date startTime = new SimpleDateFormat("HH:mm:ss")
                    .parse(argStartTime);
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startTime);

            // Current Time
            java.util.Date currentTime = new SimpleDateFormat("HH:mm:ss")
                    .parse(argCurrentTime);
            Calendar currentCalendar = Calendar.getInstance();
            currentCalendar.setTime(currentTime);

            // End Time
            java.util.Date endTime = new SimpleDateFormat("HH:mm:ss")
                    .parse(argEndTime);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endTime);

            //
            if (currentTime.compareTo(endTime) < 0) {

                currentCalendar.add(Calendar.DATE, 1);
                currentTime = currentCalendar.getTime();

            }

            if (startTime.compareTo(endTime) < 0) {

                startCalendar.add(Calendar.DATE, 1);
                startTime = startCalendar.getTime();

            }
            //
            if (currentTime.before(startTime)) {

                System.out.println(" Time is Lesser ");

                valid = false;
            } else {

                if (currentTime.after(endTime)) {
                    endCalendar.add(Calendar.DATE, 1);
                    endTime = endCalendar.getTime();

                }

                System.out.println("Comparing , Start Time /n " + startTime);
                System.out.println("Comparing , End Time /n " + endTime);
                System.out
                        .println("Comparing , Current Time /n " + currentTime);

                if (currentTime.before(endTime)) {
                    System.out.println("RESULT, Time lies b/w");
                    valid = true;
                } else {
                    valid = false;
                    System.out.println("RESULT, Time does not lies b/w");
                }

            }
            return valid;

        } else {
            throw new IllegalArgumentException(
                    "Not a valid time, expecting HH:MM:SS format");
        }

    }

RESULT

Comparing , Start Time /n    Thu Jan 01 23:00:00 IST 1970
Comparing , End Time /n      Fri Jan 02 02:00:00 IST 1970
Comparing , Current Time /n  Fri Jan 02 01:50:00 IST 1970
RESULT, Time lies b/w

#5


7  

 Calendar now = Calendar.getInstance();

 int hour = now.get(Calendar.HOUR_OF_DAY); // Get hour in 24 hour format
 int minute = now.get(Calendar.MINUTE);

 Date date = parseDate(hour + ":" + minute);
 Date dateCompareOne = parseDate("08:00");
 Date dateCompareTwo = parseDate("20:00");

 if (dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
    //your logic
 }

 private Date parseDate(String date) {

    final String inputFormat = "HH:mm";
    SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
    try {
         return inputParser.parse(date);
    } catch (java.text.ParseException e) {
         return new Date(0);
    }
 }

Further more, to be more precise, If you compare a time between an interval more than 00:00 to 24:00 of that day, you need to parse the day too.

此外,更准确地说,如果您比较当天00:00到24:00之间的时间间隔,您还需要解析当天。

#6


2  

Sounds to me that your problem is an OR situation... You want to check if time1 > 20:11:13 OR time1 < 14:49:00.

听我说你的问题是OR情况......你想检查时间1> 20:11:13或时间1 <14:49:00。

There will never be a time greater to 20:11:13 that exceeds your range through the other end (14:49:00) and viceversa. Think of it as if you are checking that a time is NOT between a properly ordered couple of timestamps.

永远不会有超过20:11:13的时间超过你的范围到另一端(14:49:00),反之亦然。可以把它想象成你正在检查时间是否在正确排序的时间戳之间。

#7


2  

Following method checks whether 'validateTime' is between 'startTime' & 'endTime' or not while considering possibility that 'endTime' can be a next day. To use it properly parse your dates in "HH:mm" formant.

以下方法检查'validateTime'是否介于'startTime'和'endTime'之间,同时考虑'endTime'可能是第二天的可能性。要使用它,请在“HH:mm”共振峰中正确解析日期。

 public static final boolean isBetweenValidTime(Date startTime, Date endTime, Date validateTime)
 {
        boolean validTimeFlag = false;

        if(endTime.compareTo(startTime) <= 0)
        {
            if(validateTime.compareTo(endTime) < 0 || validateTime.compareTo(startTime) >= 0)
            {
                 validTimeFlag = true;
            }
        }
        else if(validateTime.compareTo(endTime) < 0 && validateTime.compareTo(startTime) >= 0)
        {
             validTimeFlag = true;  
        }

        return validTimeFlag;
 }

#8


2  

After reading a few replies, I feel the writing is too complicated. Try my code

看了几篇回复后,我觉得写作太复杂了。试试我的代码

 public static boolean compare(String system_time, String currentTime, String endtimes) {
    try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");

        Date startime = simpleDateFormat.parse("19:25:00");
        Date endtime = simpleDateFormat.parse("20:30:00");

        //current time
        Date current_time = simpleDateFormat.parse("20:00:00");

    if (current_time.after(startime) && current_time.before(endtime)) {
            System.out.println("Yes");
            return true;
      }
    else if (current_time.after(startime) && current_time.after(endtime)) {
         return true; //overlap condition check
      }
     else {
            System.out.println("No");
            return false;
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return false;
 } 

#9


1  

As with the help of @kocko, the complete working code is as below:

在@kocko的帮助下,完整的工作代码如下:

try{
Date time11 = new SimpleDateFormat("HH:mm:ss").parse("20:11:13");
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time11);

Date time22 = new SimpleDateFormat("HH:mm:ss").parse("14:49:00");
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time22);

Date currentTime = new SimpleDateFormat("HH:mm:ss").parse("00:00:00");
Calendar startingCalendar = Calendar.getInstance();
startingCalendar.setTime(currentTime);
startingCalendar.add(Calendar.DATE, 1);



//let's say we have to check about 01:00:00
String someRandomTime = time1;
Date d = new SimpleDateFormat("HH:mm:ss").parse(someRandomTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);

if(startingCalendar.getTime().after(calendar1.getTime()))
{
calendar2.add(Calendar.DATE, 1);

    calendar3.add(Calendar.DATE, 1);
}

Date x = calendar3.getTime();

if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) 
{
System.out.println("Time is in between..");
}
else
{
System.out.println("Time is not in between..");
}

} catch (ParseException e) 
{
e.printStackTrace();
}

#10


1  

strip colons from the $time, $to and $from strings, convert to int and then use the following condition to check if the time is between from and to. Example is in php, but shouldn't matter.

从$ time中剥离冒号,从字符串中取$和$,转换为int,然后使用以下条件检查时间是否在from和to之间。示例是在php中,但不应该重要。

if(($to < $from && ($time >= $from || $time <= $to)) ||
    ($time >= $from && $time <= $to)) {
    return true;
}

#11


1  

The Actual working function will be as follows

实际工作功能如下

public static boolean isTimeBetweenTwoTime(Date startTime, Date stopTime, Date currentTime) {
    //Start Time
    Calendar StartTime = Calendar.getInstance();
    StartTime.setTime(startTime);
    //Current Time
    Calendar CurrentTime = Calendar.getInstance();
    CurrentTime.setTime(currentTime);
    //Stop Time
    Calendar StopTime = Calendar.getInstance();
    StopTime.setTime(stopTime);

    if (stopTime.compareTo(startTime) < 0) {
        if (CurrentTime.compareTo(StopTime) < 0) {
            CurrentTime.add(Calendar.DATE, 1);
        }
        StopTime.add(Calendar.DATE, 1);
    }
    return CurrentTime.compareTo(StartTime) >= 0 && CurrentTime.compareTo(StopTime) < 0;
}

#12


1  

In your case the starting time (20:11:13) is larger than the ending time (14:49:00). It is a reasonable assumption that you could solve the problem by adding a day on the ending time or subtracting a day from the starting time. if you do so, you will be trapped because you do not know on which day the testing time is.

在您的情况下,开始时间(20:11:13)大于结束时间(14:49:00)。可以合理地假设您可以通过在结束时间添加一天或从开始时间减去一天来解决问题。如果你这样做,你将被困,因为你不知道测试时间是哪一天。

You can avoid this trap by checking whether your testing time is between the ending time and starting time. If true, then result is "not in between"; else result is "well in between".

您可以通过检查测试时间是否在结束时间和开始时间之间来避免此陷阱。如果是,那么结果是“不介于”之间;否则结果是“介于两者之间”。

Here is the function in JAVA I have been using. It works so far for me. Good luck.

这是我一直在使用的JAVA中的功能。它对我来说到目前为止。祝你好运。

boolean IsTimeInBetween(Calendar startC, Calendar endC, Calendar testC){
    // assume year, month and day of month are all equal.
    startC.set(1,1,1);
    endC.set(1,1,1);
    testC.set(1,1,1);

    if (endC.compareTo(startC) > 0) {
        if ((testC.compareTo(startC)>=0) && (testC.compareTo(endC)<=0)) {
            return true;
        }else {
            return false;
        }
    }else if  (endC.compareTo(startC) < 0) {
        if ((testC.compareTo(endC) >= 0) && (testC.compareTo(startC) <= 0)) {
            return false;
        } else {
            return true;
        }
    } else{ // when endC.compareTo(startC)==0, I return a ture value. Change it if you have different application. 
        return true;
    }
}

To create a Calender instance you can use:

要创建日历实例,您可以使用:

Calendar startC = Calendar.getInstance();
startC.set(Calendar.HOUR_OF_DAY, 20);
startC.set(Calendar.MINUTE,11);
startC.set(Calendar.SECOND,13);

#13


1  

Java 8 - LocalDateTime

Java 8 - LocalDateTime

What about this?

那这个呢?

final LocalDateTime now = LocalDateTime.now();
final LocalDateTime minRange = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 22, 30); //Today, 10:30pm
LocalDateTime maxRange = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 6, 30); //Tomorrow, 6:30am
maxRange = maxRange.plusDays(1); //Ensures that you don't run into an exception if minRange is the last day in the month.
if (now.isAfter(minRange) && now.isBefore(maxRange)) {
    //Action
}

#14


1  

Using LocalTime would simply ignore the Date value:

使用LocalTime只会忽略Date值:

public class TimeIntervalChecker {

static final LocalTime time1 = LocalTime.parse( "20:11:13"  ) ;
static final LocalTime time2 = LocalTime.parse( "14:49:00" ) ;

    public static void main(String[] args) throws java.lang.Exception {

        LocalTime nowUtcTime = LocalTime.now(Clock.systemUTC());

        if (nowUtcTime.isAfter(time1) && nowUtcTime.isBefore(time2)){
              System.out.println(nowUtcTime+" is after: "+ time1+" and before: "+ time2);
        } 

}

#15


1  

In the code snipet below, it is being verified that if the current time (can be any) exists between start and end time or not:

在下面的代码snipet中,正在验证如果当前时间(可以是任何时间)存在于开始和结束时间之间:

        Calendar startTimeCal = Calendar.getInstance();
        startTimeCal.setTime(startTime);

        int startTimeHour = startTimeCal.get(Calendar.HOUR_OF_DAY);

        if (startTimeHour == 0){
            startTimeHour = 24;
        }

        int startTimeMinutes = startTimeCal.get(Calendar.MINUTE);

        Calendar curTimeCal = Calendar.getInstance();
        curTimeCal.setTime(currentTime);

        int curTimeHour = curTimeCal.get(Calendar.HOUR_OF_DAY);
        int curTimeMinutes = curTimeCal.get(Calendar.MINUTE);

        Calendar endTimeCal = Calendar.getInstance();
        endTimeCal.setTime(endTime);

        int endTimeHour = endTimeCal.get(Calendar.HOUR_OF_DAY);

        if (endTimeHour == 0) {
            endTimeHour = 24;
        }

        int endTimeMinutes = endTimeCal.get(Calendar.MINUTE);

        if (((curTimeHour > startTimeHour) || (curTimeHour == startTimeHour && curTimeMinutes >= startTimeMinutes)) &&
                ((curTimeHour < endTimeHour) || (curTimeHour == endTimeHour && curTimeMinutes <= endTimeHour))) {
          //time exists between start and end time
        } else {
              //time doesn't exist between start and end time
        }

#16


1  

sorry for the sudo code..I'm on a phone. ;)

对不起sudo代码..我在打电话。 ;)

between = (time < string2 && time > string1);
if (string1 > string2)  between = !between;

if they are timestamps or strings this works. just change the variable names to match

如果它们是时间戳或字符串,这是有效的。只需更改变量名称即可

#17


0  

Logically if you do the following you should always be ok granted we use military time...

从逻辑上讲,如果您执行以下操作,您应该总是可以使用军事时间...

if start time is greater than end time add 24 to end time else use times as is

如果开始时间大于结束时间,则将24添加到结束时间,否则使用时间

compare current time to be inbetween start and end time.

比较当前时间在开始和结束时间之间。

#18


0  

As many people noticed, it's not a date problem, it's a logic problem. Let's assume a day is splitted in two intervals: one lies between 20:11:13 and 14:49:00, while the other lies between 14:49:00 and 20:11:13 (which interval the extremes belong is up to you). If you want to check if a certain time is included in the 20:11:13/14:49:00 one, the one you're interested of, just check if it's included in the other one, 14:49:00/20:11:13, which is much easier because the natural order of the numbers, and then negate the result.

正如许多人注意到的那样,这不是日期问题,而是一个逻辑问题。让我们假设一天分为两个区间:一个位于20:11:13到14:49:00之间,而另一个位于14:49:00到20:11:13之间(极端所属的区间是您)。如果您想检查20:11:13/14:49:00中是否包含一个您感兴趣的时间,请检查它是否包含在另一个中,14:49:00 / 20:11:13,这更容易因为数字的自然顺序,然后否定结果。

#19


-2  

This is working, but needs some improvement.

这是有效的,但需要一些改进。

long timeToSeconds(String time){
    long ret=0;
    String[] ar = time.split("\\:");
    for(int i=0;i < ar.length ; i++){
        ret+= Long.valueOf(ar[i])* Math.pow(60,(2-i)); // (60^(2-i));
    }
    return ret;
}
boolean isTimeBetween(String startTime, String endTime,String currentTime) {
    long lCurrentTime = timeToSeconds(currentTime);
    long lstartTime = timeToSeconds(startTime);
    long lEndTime = timeToSeconds(endTime);

    if(((lstartTime-lCurrentTime)*(lEndTime-lCurrentTime)*(lstartTime-lEndTime))>0){
        return true;
    }else{
        return false;
    }
}

Modify your code like this-

像这样修改你的代码 -

 public void getTimeSpans(){
    boolean firstTime = false, secondTime = false;

    if(isTimeBetween("20:11:13" ,"14:49:00",time1)
    {
        firstTime = true;
    }

    if(isTimeBetween("20:11:13" ,"14:49:00",time2)
    {
        secondTime = true;
    }
}