java - java中的millis字符串格式

标签 java string format decimal

我有这个代码:

  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

最佳答案

您尝试使用 4 个参数获取格式 %02d:%02d.%03d (此处您给出了 3 个)。所以你错过了。格式化了 second,而不是格式化了 milli

代码应该是:

String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, milli)

关于java - java中的millis字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31809689/

相关文章:

java - 如何使用java从字符串中删除一个字符

java - 如何将拉丁 unicode 字符替换为 [a-z] 字符

java - 使用反射设置字段 - String 没有 valueOf(String) 方法

c++ - 在字符串末尾添加 double (C++)

perl - 如何使用 Perl 将文件格式从 Unix 更改为 DOS?

java - 将频率应用于数组中的元素

java - Android textview 不显示正确的字符

regex - 使用正则表达式检测序列

swift - Swift 中的 NSString 格式未达到预期效果

python - 在 Python 中打开 Alteryx .yxdb 文件?