Chirag Gohil Chirag Gohil - 1 year ago 68
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 Source

Parse it into a hava LocalTime using this API

LocalTime.parse(userInput, hhmmFormatter)

(see API documentation here

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


which fits your case perfectly. More details here

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

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.