-3

I have a time in 24hour format like this 23:08 Now I want to get the remaining hour and minute from now to that time of the day in this example format like 3h 10m, how can I get this? any idea? I have got solutions in other threads but all of them calculates date also, but I dont want the date, it will always calculate from today and if the time is passed from today then it will give remaining time of the next day.

Reyjohn
  • 2,654
  • 9
  • 37
  • 63

2 Answers2

2

This will give you the current time

        Calendar cal = Calendar.getInstance();  
        Date d1 = cal.getTime();// current time

This will calculate the difference in minutes and in hours

        Date d2;//your time
        long diff = d2.getTime() - d1.getTime();
        long diffHours = diff / (60 * 60 * 1000);
        long diffMinutes = diff / (60 * 1000) % 60;
Emil
  • 2,786
  • 20
  • 24
1

Sorry, I misunderstood the question. Here is the new answer.

public static void main(String[] args) {
    Calendar cal = Calendar.getInstance();
    int nowHour = cal.get(Calendar.HOUR_OF_DAY);
    int nowMin  = cal.get(Calendar.MINUTE);
    System.out.printf("Now is: %02d:%02d%n", nowHour, nowMin);
    test(nowHour, nowMin, "00:00");
    test(nowHour, nowMin, "01:00");
    test(nowHour, nowMin, "11:59");
    test(nowHour, nowMin, "12:00");
    test(nowHour, nowMin, "23:08");
    test(nowHour, nowMin, "23:59");
}
private static void test(int nowHour, int nowMin, String endTime) {
    Matcher m = Pattern.compile("(\\d{2}):(\\d{2})").matcher(endTime);
    if (! m.matches())
        throw new IllegalArgumentException("Invalid time format: " + endTime);
    int endHour = Integer.parseInt(m.group(1));
    int endMin  = Integer.parseInt(m.group(2));
    if (endHour >= 24 || endMin >= 60)
        throw new IllegalArgumentException("Invalid time format: " + endTime);
    int minutesLeft = endHour * 60 + endMin - (nowHour * 60 + nowMin);
    if (minutesLeft < 0)
        minutesLeft += 24 * 60; // Time passed, so time until 'end' tomorrow
    int hours = minutesLeft / 60;
    int minutes = minutesLeft - hours * 60;
    System.out.println(hours + "h " + minutes + "m until " + endTime);
}

Output:

Now is: 02:15
21h 45m until 00:00
22h 45m until 01:00
9h 44m until 11:59
9h 45m until 12:00
20h 53m until 23:08
21h 44m until 23:59
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • your answer does some work but Its not accurate just shows some random value, can you check if there is something wrong? – Reyjohn Aug 24 '15 at 06:01
  • i have got your answer but it is calculating as now it is 00:00 AM, can you calculate it from the exact time of now? – Reyjohn Aug 24 '15 at 06:06