Java 以hh:mm格式输入时间
我正在用Java创建一个应用程序,我有一个文本字段,在其中输入开始时间,另一个字段输入结束时间。在这些输入之后,我想看看表hh:mm中的时差 例如: 开始时间:12:00Java 以hh:mm格式输入时间,java,Java,我正在用Java创建一个应用程序,我有一个文本字段,在其中输入开始时间,另一个字段输入结束时间。在这些输入之后,我想看看表hh:mm中的时差 例如: 开始时间:12:00 结束时间:14:30 结果:2:30 从日期字段中获取以毫秒为单位的时间。从“截止日期”中减去“起始日期”。例如 toDate.getTime() - fromDate.getTime() 然后你有毫秒的时差,简单的计算成秒,小时,天等等 milliseconds / 1000 例如秒等。这将有助于您了解如何解析和格式化日
结束时间:14:30 结果:2:30
从日期字段中获取以毫秒为单位的时间。从“截止日期”中减去“起始日期”。例如
toDate.getTime() - fromDate.getTime()
然后你有毫秒的时差,简单的计算成秒,小时,天等等
milliseconds / 1000
例如秒等。这将有助于您了解如何解析和格式化日期对象 要分析文本字段中的日期,请使用
// use "hh:mm" if you work in 12-hour format or
// use "HH:mm" if you work in 24-hour format
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
try
{
Date date = dateFormat.parse(startTextField.getText());
}
catch (ParseException e)
{
//TODO don't forget process exception
e.printStackTrace();
}
到目前为止给出的两个答案都是正确的,但我认为最好将它们结合起来使用 像这样:
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
try {
Date startDate = dateFormat.parse(startTextField.getText());
Date endDate = dateFormat.parse(endTextField.getText());
long differenceMillis = endDate.getTime() - startDate.getTime();
resultTextField.setText(dateFormat.format(new Date(differenceMillis)));
} catch (ParseException e) {
resultTextField.setText("ERROR");
}
有关所有编码方案,请参阅。请注意,此方法将以天为单位减少差异,并且仅报告小时数 那没用?