【问题标题】:Converting seconds to human readable format MM:SS Java [duplicate]将秒转换为人类可读格式 MM:SS Java [重复]
【发布时间】:2014-07-26 17:11:19
【问题描述】:

如何将 long int of seconds 转换为人类可读的格式

MM:SS

只有 SS 应该是 0 填充所以

long = 67 -> 1:07

【问题讨论】:

  • 使用/%operator。

标签: java time format string-formatting


【解决方案1】:

一些算术:

long min = value / 60;
long second = value % 60 ;
String value = min + ":" + (second > 10 ? "" : "0") + second;

【讨论】:

    【解决方案2】:

    使用整数除以 60 将秒转换为整分钟。 60 秒的模数 (%) 将给出“剩余”秒数。然后使用字符串转换来检查 0 填充的必要性。

    int minutes = (total / 60);
    int seconds = (total % 60);
    String secs = Integer.toString(seconds);
    if (seconds < 10) {
       secs = "0" + seconds;
    }
    String time = minutes + ":" + secs;
    

    【讨论】:

    • +1 虽然你有不必要的演员int
    • 没有意义浪费空间存储长。说实话,我把原版读成双重的,因此是演员表。现已修复。
    【解决方案3】:
    int duration = 90;
    int min = duration/60;
    int sec = duration%60;
    String formattedTime = String.format("%d:%02d",min,sec);
    

    【讨论】:

      【解决方案4】:
      String readable = String.format("%d:%02d", s/60, s%60);
      

      【讨论】:

      • +1 更优雅!
      • +1 用于内置库和更短更简单的代码。
      猜你喜欢
      • 2021-01-14
      • 2021-09-11
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      相关资源
      最近更新 更多