-1

I have following time for a given day which is in sting format.

      "begin_time_tz": "00:00 DST",
      "end_time_tz": "07:30 DST",

I have to find the difference between them in java. Please help me to find the difference and convert back to string

Note: Date is in 24 hour format(00:00 -- 23:59)

2 Answers2

0

You can use the below method to get the time difference, just pass HH:MM without the timezone.

public long getTimeDifference(String time1, String time2) throws ParseException{
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        Date date1 = format.parse(time1);
        Date date2 = format.parse(time2);
        long difference = date2.getTime() - date1.getTime();
        return difference/1000;
    }
Umais Gillani
  • 608
  • 4
  • 9
0

using Java8 DateTime API we can get the Duration between two LocalTime

    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME;
    String[] arr = new String[] { "00:00", "07:30" };
    LocalTime start = LocalTime.parse(arr[0], formatter);
    LocalTime end = LocalTime.parse(arr[1], formatter);
    Duration duration = Duration.between(start, end);
    System.out.println(duration);

output

PT7H30M

Hour minute conversion

static final int SECONDS_PER_MINUTE = 60;
static final int MINUTES_PER_HOUR = 60;
static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR;

long seconds = duration.getSeconds();
long hours = seconds / SECONDS_PER_HOUR;
int minutes = (int) ((seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);
System.out.println("Duration " + hours + " hours " + minutes + " minutes ");

output

Duration 7 hours 30 minutes 
Saravana
  • 12,647
  • 2
  • 39
  • 57