binu j binu j - 1 month ago 11
Java Question

How to get Remaining time in Hour:mins:seconds

I need to get the Remaining time in Hour:mins:seconds to 6:20 PM every day. used this code , but every time i need to change dateInString variable to the current date, Is there any simple way to get the remaining time.

SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "21-09-2016 18:20:00";
Date date = sdf.parse(dateInString);

System.out.println(dateInString);
System.out.println("Date - Time in milliseconds : " + date.getTime());

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println("Calender - Time in milliseconds : " + calendar.getTimeInMillis());

Answer

Assuming that you cannot use Java 8, here is how you could proceed:

// Create the date corresponding to today at 18:20:00
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 18);
cal.set(Calendar.MINUTE, 20);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

// Create the diff date
Calendar diff = Calendar.getInstance();
diff.setTimeInMillis(cal.getTimeInMillis() - diff.getTimeInMillis());

// Display the diff in HH:mm:ss
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(diff.getTime()));

NB: This approach will work even if the current date is after 18:20:00 without adding anything to the code