2

I have the estimated time the it would take for a particular task in minutes in a float. How can I put this in a JFormattedTextField in the format of HH:mm:ss?

jzd
  • 23,473
  • 9
  • 54
  • 76
davidahines
  • 3,976
  • 16
  • 53
  • 87

2 Answers2

6

For a float < 1440 you can get around with Calendar and DateFormat.

float minutes = 100.5f; // 1:40:30

Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.add(Calendar.MINUTE, (int) minutes);
c.add(Calendar.SECOND, (int) ((minutes % (int) minutes) * 60));
final Date date = c.getTime();

Format timeFormat = new SimpleDateFormat("HH:mm:ss");
JFormattedTextField input = new JFormattedTextField(timeFormat);
input.setValue(date);

But be warned that if your float is greater than or equal to 1440 (24 hours) the Calendar method will just forward a day and you will not get the expected results.

Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118
4

JFormattedTextField accepts a Format object - you could thus pass a DateFormat that you get by calling DateFormat#getTimeInstance(). You might also use a SimpleDateFormat with HH:mm:ss as the format string.

See also: http://download.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html#format


If you're not restricted to using a JFormattedTextField, you might also consider doing your own formatting using the TimeUnit class, available since Java 1.5, as shown in this answer: How to convert Milliseconds to "X mins, x seconds" in Java?

Community
  • 1
  • 1
no.good.at.coding
  • 20,221
  • 2
  • 60
  • 51
  • 1
    @dah Do you have a base `Date` that you can work with i.e. do you have the time *from* which it's going to take, say, 5 minutes, to do finish the task? – no.good.at.coding May 06 '11 at 17:54
  • Nope. it's only recorded in decimal minutes. – davidahines May 06 '11 at 17:59
  • I think I'm just going to just convert minutes to seconds to millis then use that in a date constructor and use your method. – davidahines May 06 '11 at 18:00
  • 2
    @dah I don't think that will work, you will still need a base `Date` object to work with - just milliseconds from a value like 5 minutes will only give you a time relative to the start of the epoch (January 1, 1970, 00:00:00 GMT). See my edited answer for how you might format it the way you want, quite easily, with the `TimeUnit` class. – no.good.at.coding May 06 '11 at 18:04
  • Isn't 5 minutes from the epoch the same as five minutes from x. – davidahines May 06 '11 at 18:42
  • @dah, yes. But it may not get you the result you expect. Try this code: `System.out.println(new Date(0)); System.out.println(new Date(5 * 60 * 1000));` One option that might be good for you is using `TimeUnit` and the pointed article to implement your own Format class (just extend java.text.Format and implement the abstract methods). This way you get the best of both worlds. – Anthony Accioly May 06 '11 at 18:53