java JTextField 时间以 HH:mm:ss 表示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5914909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JTextField time in HH:mm:ss
提问by davidahines
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
?
我在浮动中以分钟为单位估计了特定任务所需的时间。我怎样才能把它放在一个 JFormattedTextField 的格式中HH:mm:ss
?
回答by Anthony Accioly
For a float < 1440 you can get around with Calendar
and DateFormat
.
对于 float < 1440,您可以使用Calendar
和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.
但请注意,如果您的浮动时间大于或等于 1440(24 小时),则 Calendar 方法只会向前推一天,您将无法获得预期的结果。
回答by no.good.at.coding
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.
JFormattedTextField
接受一个Format
对象 - 因此DateFormat
您可以通过调用DateFormat#getTimeInstance()
. 您还可以使用SimpleDateFormat
withHH: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?
如果您不限于使用 a JFormattedTextField
,您还可以考虑使用TimeUnit
自 Java 1.5 起可用的类进行自己的格式化,如以下答案所示:How to convert Milliseconds to "X mins, x seconds" in Java?