-1

I have 2 TextViews, timeStarted, and timeIn. Both of their text values came from a database via PHP display like this:

11:18 AM

Now, I want to calculate their differences in minutes and display it to another TextView called Differences. After that, I want to make a condition where if time in is greater than 15 minutes to time started it will display a text "late" into another TextView called status.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110

1 Answers1

2

You can parse the times into LocalTime and then find the difference in terms of the desired unit (e.g. ChronoUnit.MINUTES) using LocalTime#until. Based on the value of the difference, you can make a decision.

Demo:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("hh:mm a", Locale.US);
        LocalTime time1 = LocalTime.parse("11:18 AM", dtf);
        LocalTime time2 = LocalTime.parse("11:45 AM", dtf);
        long minutes = Math.abs(time1.until(time2, ChronoUnit.MINUTES));

        if (minutes > 15) {
            System.out.println("Do this");
            // ...
        } else {
            System.out.println("Do that");
            // ...
        }
    }
}

Output:

Do this

* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. 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 and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110