我有这段代码:
public String calculateHoursFromMilliSeconds(long totalMilliSeconds) {
long totalSeconds = totalMilliSeconds / 1000;
long milli = totalMilliSeconds % 1000;
long hours = totalSeconds / 3600;
long minutes = (totalSeconds % 3600) / 60;
long seconds = totalSeconds % 60;
return String.format("%02d:%02d.%03d", hours, minutes, seconds, milli);
}
然而
输入412毫米
我得到输出00:00.004
而不是00:00.412
输入60412毫秒
我得到输出01:00.004
而不是01:00.412
答案 0 :(得分:3)
您尝试使用4个参数获取格式%02d:%02d.%03d
(此处已给出3)。所以你错过了milli
。 milli
已格式化
second
格式化
代码应该是:
String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, milli)
答案 1 :(得分:2)
格式字符串中只有一个%02d
。试试这个:
return String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, milli);
// HH : MM : SS . milli
412: 00:00:00.412
60412: 00:01:00.412
或者,如果是hours
,请移除0
。添加以下条件:
if(hours == 0) return String.format("%02d:%02d.%03d", minutes, seconds, milli);
答案 2 :(得分:1)
如果您有兴趣将Epoch转换为java可读格式,请执行以下操作:
String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));
或使用日历逐个获取:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millisec*1000);
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
等
答案 3 :(得分:-1)
这应该有效:
public String calculateHoursFromMilliSeconds(long totalMilliSeconds) {
long totalSeconds = totalMilliSeconds / 1000;
long milli = totalMilliSeconds % 1000;
long hours = totalSeconds / 3600;
long minutes = (totalSeconds % 3600) / 60;
long seconds = totalSeconds % 60;
DecimalFormat formatter = new DecimalFormat("###");
formatter.setRoundingMode(RoundingMode.HALF_UP);
String millisStr = formatter.format(milli);
return String.format("%02d:%02d."+millisStr, hours, minutes, seconds);
}