简体   繁体   English

JTextField时间,以HH:mm:ss为单位

[英]JTextField time in HH:mm:ss

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 ? 如何将其放入HH:mm:ss格式的JFormattedTextField中?

For a float < 1440 you can get around with Calendar and DateFormat . 对于小于1440的float,可以使用CalendarDateFormat

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. 但是请注意,如果您的浮动时间大于或等于1440(24小时),则Calendar方法将只向前一天,您将无法获得预期的结果。

JFormattedTextField accepts a Format object - you could thus pass a DateFormat that you get by calling DateFormat#getTimeInstance() . JFormattedTextField接受Format对象-因此你可以传递一个DateFormat ,你得到通过调用DateFormat#getTimeInstance() You might also use a SimpleDateFormat with HH:mm:ss as the format string. 您也可以使用SimpleDateFormat HH:mm:ss SimpleDateFormat HH:mm:ss作为格式字符串。

See also: http://download.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html#format 另请参阅: 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? 如果不限于使用JFormattedTextField ,您还可以考虑使用TimeUnit类(自Java 1.5开始提供)进行自己的格式设置,如此答案所示: 如何在Java中将毫秒转换为“ X分钟,x秒”?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM