I am on a project to capture the interval time in hh:mm. I have 2 buttons named btnTimeOut & btnTimeIn both capturing the system time when clicked. The requirement is to get the interval between the btnTimeOut & btnTime in hh:mm, etc. 12:30 - 10:00 = 02:30 (hh:mm).
Currently I used the following codes for the interval but it returns as minutes, etc. 12:30 - 10:00 = 150 minutes.
String timeOut = lblTimeOut.getText();
String timeIn = lblTimeIn2.getText();
SimpleDateFormat format = new SimpleDateFormat("hh:mm");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(timeOut);
d2 = format.parse(timeIn);
}
catch (Exception e){
e.printStackTrace();
}
long diff = d2.getTime() - d1.getTime();
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
lblSurface.setText(String.valueOf(diffMinutes));
How to get the duration in the form hh:mm
?
I used Joda time and return with Invalid format: "12:19" is malformed at ":19". As for my other buttons which trigger the display time.
DateFormat timeFormat = new SimpleDateFormat("hh:mm");
Date date = new Date();
String time = timeFormat.format(date);
lblTimeIn2.setText(time);
Timer timer = new Timer(1000, timerListener);
// to make sure it doesn't wait one second at the start
timer.setInitialDelay(0);
timer.start();
}
I've no idea what is wrong, do I need to use joda time for displaying time for my other label too?
When you are getting minutes, it includes the hours as well. Simply divide the minutes by
60
to get the hours and update the minutes with remainder value of the division as below.Finally set the hours and minutes in the text:
Since
":"
is appended in between, it should be fine because of implicit conversion.E.G.
Output
I, personally, would use JodaTime as it takes into account things like difference between days (ie the difference between 23:30-02:30) and has nice inbuilt formatters
Which will output
02:00
Extended example
Your questions a little vague, so I've done a wide example. Mark, basically auto fills the fields with the current time.
There is little validation ;)