The correct format between two times in Java
I tried to calculate the number of hours between two in Java I'm using joda time library to format it The program can pull the time entered in the text box and text box Put them in the Localtime variable:
LocalTime startTime1; LocalTime airTime1; LocalTime foamTime1; LocalTime scTime1;
Then, the start button does the following
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm"); startTime1 = formatter.parseLocalTime(startField2.getText()); airTime1 = formatter.parseLocalTime(airField.getText()); foamTime1 = formatter.parseLocalTime(fTimeField2.getText()); scTime1 = formatter.parseLocalTime(remainingField2.getText());
Then I want to calculate the time between airtime1 and starttime1 & I'm trying to use the following:
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm"); Minutes difference = ((Minutes.minutesBetween(airTime1,startTime1))); LocalTime remaining1 = formatter.parseLocalTime(difference);
The remaining 1 should maintain the duration value between airtime1 & startTime1. The rest is then written to the image
Graphics g = image2.getGraphics(); g.setFont(g.getFont().deriveFont(30f)); g.drawString((String.valueOf(remaining1)),100,100); g.dispose();
I finally got an error that minutes cannot be converted to strings Which variable type do I need to use to make it work?
thank you
Solution
The fundamental problem you encounter is that duration is a different concept from the actual date and time line
Minutes difference = ((Minutes.minutesBetween(airTime1,startTime1))); LocalTime remaining1 = formatter.parseLocalTime(difference);
It doesn't make sense because the idea of converting duration to date time doesn't make sense What is the date and time for "3 minutes"? The closest thing I can imagine is a pair of dates and times, one for the beginning and one for the end, but that's what you already have
Minutes means (or maybe the hours representation, based on the use case you declared) that you actually want, and I think you're just over thinking about it Without further conversion, just use it to build the string you want:
// Get difference,same as before Minutes difference = ((Minutes.minutesBetween(airTime1,startTime1))); // Create string representation of difference // (Minutes.toString() representation exists but is hard to read) String diffStr = difference.getMinutes() / 60.0 + " hours" // for,e.g.,"3.5 hours" // Re-use your old graphics code with new string Graphics g = image2.getGraphics(); g.setFont(g.getFont().deriveFont(30f)); g.drawString(diffStr,100); g.dispose();