0

Having some trouble working this one out. I'm making a workclock simply for myself to help calculate how many hours I worked that day. I have two pickers, one for the start time and one for the finish time. Both pickers format the selected time into a string. Now I just need to find the hours that have passed between the start string and the finish string. I don't work over a date change so no need to work out the days/date which previously confused me here -> Calculate date/time difference in java

These are my picker listeners.

private TimePickerDialog.OnTimeSetListener startPickerListener = new TimePickerDialog.OnTimeSetListener() {

    public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
        startHour = selectedHour;
        startMinute = selectedMinute;

        startTime.setText(new StringBuilder().append(padding_str(startHour)).append(":").append(padding_str(startMinute)));

    }
};
private TimePickerDialog.OnTimeSetListener finishPickerListener = new TimePickerDialog.OnTimeSetListener() {

    public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
        finishHour = selectedHour;
        finishMinute = selectedMinute;

        finishTime.setText(new StringBuilder().append(padding_str(finishHour)).append(":").append(padding_str(finishMinute)));

    }
};

Any help would be GREATLY appreciated! Cheers! (If you need any more info just lemme know.)

Community
  • 1
  • 1
  • You are asking two questions, not one. (a) Parsing string into a time value, (b) Calculating elapsed time. Both have been asked and answered many times on StackOverflow. – Basil Bourque Apr 05 '14 at 04:56
  • I understand that they have been asked multiple times before, but non of them have helped. They're all picking times between point A to current time, not Time A and time B regardless what the time currently is. and if they're not doing that, they're using date and time but rightfully I couldn't care less what the date is because like hell my boss would be getting me to work 24+ hours or even so late/early in the night/morning. I'm just trying to make a basic calculator. nothing more nothing less. – Deal-or-die Apr 13 '14 at 03:31
  • If you want time without date, does my answer solve your question? The point of my comment is that you should be able to construct the answer yourself. If you perform searches such as "joda date parse" and "joda calculate time", or "joda elapsed", you will find plenty of code and examples. – Basil Bourque Apr 13 '14 at 04:26
  • I suggest that you should be concerned with date. Because of daylight saving time and other anomalies, generally time work should be done with date *and* time considered and tracked together. This may sound superfluous to you, but eventually the pain will teach you otherwise. – Basil Bourque Apr 13 '14 at 04:29
  • Personally I think I need to go right back to the starting basics... I don't completely understand what should be 'public', 'private', 'static' Ect ect... I don't know how to call those functions to do their work onClick. I read, followed and understood the 'Building your first app' supplied generously by android.com but that doesn't help me understand these call functions or what ever they're called... Any ideas of where to look that go more into depth on these or any better tutorials that you may know of to help? I apologise for my lack of knowledge. I do want to learn. – Deal-or-die Apr 13 '14 at 06:19
  • Yes, if new to object-oriented programming, starting off with Android and with date-time work is biting off too much. Start with simple throw-away little Java apps to master the basics. Read the excellent and fun [Head First Java](http://www.headfirstlabs.com/books/hfjava/) book (Kathy Sierra is a *genius*). Then work relevant parts of the free-of-cost online [Java Tutorial](http://docs.oracle.com/javase/tutorial/) provided by Oracle. After that, go back to trying some Android work. And put off date-time work as much as possible – it is surprisingly and maddeningly tricky stuff to get right. – Basil Bourque Apr 14 '14 at 05:22

2 Answers2

0

If you import the strings into a Date using a SimpleDateFormat you can calculate the difference in time easily. Something like this:

Date startDate = new SimpleDateFormat("HH:mm", Locale.ENGLISH).parse(startHour + ":" + startMinute);
Date endDate = new SimpleDateFormat("HH:mm", Locale.ENGLISH).parse(endHour + ":" + endMinute);
long milliDiff = endDate - startDate;
long hoursDiff = milliDiff / (60 * 60 * 1000); //Convert millisecond of difference into hours

This should work even if you do happen to work over a date change, as the milliseconds are calculated from Jan. 1, 1970 and not from the beginning of the day.

Nickel
  • 419
  • 3
  • 13
  • Would you please give me a quick simple example to this please? I apologise for my ignorance however I am only new to the app making scene. Cheers buddy! Appreciated. – Deal-or-die Apr 13 '14 at 03:33
  • When I use the 'long hoursDiff = milliDiff / (60 * 60 * 1000);' I get "milliDiff cannot be resolved to a variable" – Deal-or-die Apr 13 '14 at 10:37
  • Did you initialize milliDiff like I did in my example? If you copy and paste the four lines I wrote up there I believe they should work without any further change and hoursDiff will be the answer you need. – Nickel Apr 13 '14 at 12:17
  • Ahh yeah apologies. When I used the example you provided I got the error 'The operator - is undefined for the argument type(s) java.util.Date, java.util.Date'. Ideas? – Deal-or-die Apr 13 '14 at 13:28
  • Ack, try subtracting endDate.getTime() - startDate.getTime() instead. I missed a step. – Nickel Apr 13 '14 at 14:18
  • Ahh great! that fixed that problem. however I'm now stuck with another... Haha. `Toast.makeText(MainActivity.this, "Start Time: "+ String.valueOf(startTime.getText()) + "\nFinish Time: "+ String.valueOf(finishTime.getText()) + "\nStart Diff: "+ String.valueOf(startDate.getTime()) + "\nFinish Diff: "+ String.valueOf(finishDate.getTime()) + "\nTotal Diff: "+ String.valueOf(hoursDiff.), Toast.LENGTH_SHORT).show();` How do I put the Difference into a Toast? – Deal-or-die Apr 13 '14 at 14:29
  • Oh, additionally. `Date startDate = new SimpleDateFormat("HH:mm", Locale.ENGLISH).parse(startHour + ":" + startMinute); Date finishDate = new SimpleDateFormat("HH:mm", Locale.ENGLISH).parse(finishHour + ":" + finishMinute);` Are giving me a 'Unhandled exception type ParseException' Shall I just surround with try/catch as Eclipse suggests? Edit: Okay... Now I'm screwed... :P When using the try/catch it then wants me to initialise 'startDate' and 'finishDate'. Sigh... So confused.... – Deal-or-die Apr 13 '14 at 14:41
  • This is what I'm working with ATM. [https://www.assembla.com/code/workclock/subversion/nodes/2/MainActivity.java] Please feel free to edit if you can and I'll learn from the commits. – Deal-or-die Apr 13 '14 at 15:48
0

A Day ≠ 24 Hours

You may need dates. Because of Daylight Saving Time (DST) and other anomalies, a day may not always be 24 hours long. In the United States for example, it may be 23, 24, or 25 hours.

But if you are sure you want to work in 24-hour periods, then use the LocalTime class in Joda-Time or the new java.time package in Java 8. The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome and should be avoided. (Hence the need for java.time in Java 8)

java.time

The java.time framework includes a LocalTime class similar to Joda-Time.

LocalTime start = LocalTime.of( 9 , 0 );
LocalTime stop = LocalTime.of( 13 , 0 );

The Duration class tracks a span of time in terms of seconds and nanoseconds. See Oracle Tutorial.

Duration duration = Duration.between( start , stop );

Oddly, in Java 8 the Duration class lacks methods to obtain the number of hours part, number of minutes part, etc. You can get the span as a total number of hours and as a total number of minutes, and do the math yourself. Java 9 rectifies this lacking with new “get part” methods.

Joda-Time

You should search StackOverflow.com for "joda parse time" and "joda elapsed time". But to get you going, here is some Joda-Time 2.3 code off the top of my head (not tested, just typed).

LocalTime start = new LocalTime( 13, 10 );
LocalTime stop = new LocalTime( 13, 14 );
int minutesBetween = Minutes.minutesBetween( start, stop ).getMinutes();
Period period = new Period( start, stop );
Duration duration = period.toDuration();

The Period object can be queried for a number of hours if that is your goal.

Try calling the toString method on those objects. Search StackOverflow to learn more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154