我收到双精度输入(例如:12803.000000(,它以小时:分钟:秒为单位表示时间,请忽略点后面的值。我想要的只是使用 java 代码将此双精度值转换为 1:28:03 格式,如 HH:mm:ss 格式。如何达到预期效果?
我尝试过的代码:
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
String time = df.format(new Date((long) ((Double.parseDouble("12803.000000"))*60*60*1000)));
System.out.println("time>>"+time);
这段代码给我的输出是 16:30,这不是预期的结果。
啪!!
double x = 12803.000000;
String s = String.format("%06d", (int)x);
DateFormat format = new SimpleDateFormat("HHmmss");
Date date = format.parse(s);
我不知道您的双精度值如何表示日期,但代码可以解决您的示例问题。
下面的代码应该给你想要的结果。
public static void main (String args[]) throws ParseException {
Double value = 12803.000000;
SimpleDateFormat format = new SimpleDateFormat("HHmmss");
String intValueStr = String.valueOf(value.intValue() );
int length = intValueStr.length();
int missingDigits = 6- length;
String strForTimeParsing = intValueStr;
for(int i =0; i< missingDigits;i++){
strForTimeParsing = "0"+strForTimeParsing;
}
System.out.println("Final String after padding Zeros at the start = "+strForTimeParsing);
Date parsedDate = format.parse(strForTimeParsing);
String format1 = new SimpleDateFormat("HH:mm:ss").format(parsedDate);
System.out.println("Resulted Formatted Time = "+format1);
}
下面的代码对我有用。感谢您的帮助。
double x = 12803.000000;
String s = String.format("%06d", (int)x);
System.out.println("String val>>"+s);
DateFormat format = new SimpleDateFormat("HHmmss");
DateFormat format1 = new SimpleDateFormat("HH:mm:ss");
try {
Date date = format.parse(s);
System.out.println("date>>"+date);
System.out.println("time in String format>>"+format1.format(date));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
输出:字符串格式的时间>>01:28:03