Home > Software design >  check if user is on time (Java)
check if user is on time (Java)

Time:10-06

How to check if the user is on time.

Example: The program starts at 13:50:00, and ends at 14:50:00.

And if a user logs in, and his time is 14:30:00, he can log in. If he comes in again at 14:55:00 he can't come in again.

CodePudding user response:

You can parse the given time strings into LocalTime and then use LocalTime#isBefore and LocalTime#isAfter to find the eligibility.

Demo:

import java.time.LocalTime;

public class Main {
    static final String startTime = "13:50:00";
    static final String endTime = "14:50:00";

    public static void main(String[] args) {
        // Test
        System.out.println(canLogin("13:50:00"));
        System.out.println(canLogin("14:30:00"));
        System.out.println(canLogin("14:55:00"));
        System.out.println(canLogin("14:50:00"));
    }

    static boolean canLogin(String arrivalTime) {
        LocalTime start = LocalTime.parse(startTime);
        LocalTime end = LocalTime.parse(endTime);
        LocalTime arrival = LocalTime.parse(arrivalTime);
        return !arrival.isAfter(end) && !arrival.isBefore(start);
    }
}

Output:

true
true
false
true

ONLINE DEMO

Learn more about the modern Date-Time API* from Trail: Date Time.


* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8 APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.

  • Related