Chirag Gohil Chirag Gohil - 5 months ago 30
Android Question

Calculate end time and start time difference in mins and verify entered time in android

I have to calculate the time difference between two times(end time - start time). The time is hh:mm format and I want the difference in integer MINUTS?
One more thing how to verify that the time entered by user is between 1 to 24 hours?

Answer

Parse it into a hava LocalTime using this API

LocalTime.parse(userInput, hhmmFormatter)

(see API documentation here https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html#parse-java.lang.CharSequence-java.time.format.DateTimeFormatter-)

Do this for the two inputs. Per the documentation, this method will throw a DateTimeParseException if the format does not match hh:mm (as defined by your hhmmFormatter instance) so you can catch it and handle it however you wish.

The hhmmFormatter you can create yourself using the DateTimeFormatter.ofPattern but I would recommend simply using the standard

 DateTimeFormatter.ISO_LOCAL_TIME

which fits your case perfectly. More details here https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_TIME

So you can simply do

try {
  // NOTE: you can move these into their own try/catch so you can handle bad user input separately if you wish
  final LocalTime time1 = LocalTime.parse(userInput1, DateTimeForamatter.ISO_LOCAL_TIME);
  final LocalTime time2 = LocalTime.parse(userInput2, DateTimeForamatter.ISO_LOCAL_TIME);
  final long differenceInNanos = (time2.toNanoOfDay() - time1.toNanoOfDay());
  final long differenceInSeconds = TimeUnit.NANOSECONDS.toSeconds(differenceInNanos)
}
catch(DateTimeParseException e){
   // TODO code to handle bad user input
}

(documentation for TimeUnit https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html)

Note that you didn't note in your question if you wanted to handle the cased where users might specify times across days so I am only showing you LocalTime. You can easily convert this to the most general ZonedDateTime case and do something very similar.

Comments