Search code examples
javaandroiddatedatetimeandroid-dateutils

How do I check if current time and a custom time are within device time slot (wall clock time) of 30 mins


I have a unique issue where I have to determine 2 things.

1) if my current time and a custom time are within the same 30 min time slot ( say its 2:10pm and the custom time is 2:22pm , I want to see they are within the same time slot from 2 to 2:30 ) but shouldn't be in the same time slot if current time is 1:55pm and custom time is 2:15pm (30 min difference but not within the same device/clock time slot as one is 1:30 to 2pm and another is 2 to 2:30pm)

2) Now, within the same time slot of 30 mins, if current time is before the custom time, I want to return a true, else return a false. any way to calculate this? I am looking to add a custom function in my common utils class where I can feed it custom time and current time and see the result, so would be useful to have something generic. Any ideas?

I have looked at : Check if a given time lies between two times regardless of date and other articles but nothing describes the 30 min device/clock time slot period.

Any idea if https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateUtils.html will somehow help me manipulate this exact logic or any custom function/library in android helps with this. will be really helpful!


Solution

  • package Demo;
    
    import java.time.LocalDateTime;
    import java.time.temporal.ChronoUnit;
    import java.util.Arrays;
    public class Test1 {
        public static void main(String arg[]) {
            LocalDateTime ct = LocalDateTime.now();
            LocalDateTime custemTime = ct.plusMinutes(5);
            System.out.println(ct);
            System.out.println(custemTime)  ;
            System.out.println(isInSameSlots(ct,custemTime));
    
        }   
        static boolean   isInSameSlots(LocalDateTime ldt1, LocalDateTime ltd2) {
            Long timeDiff = ChronoUnit.MINUTES.between(ldt1, ltd2);
            if(timeDiff > 30 || timeDiff < 0) 
               return false;
            return (ldt1.getMinute() <= 30 && ltd2.getMinute() <= 30) || (ldt1.getMinute() > 30 && ltd2.getMinute() > 30 ) ? true : false; 
    
        }
    
    }
    

    case 1

    2019-06-10T18:40:09.122

    2019-06-10T18:45:09.122

    true

    Case 2 ) 2019-06-10T18:46:56.350 2019-06-10T19:06:56.350 false