如何将秒转换为hhmmss

问题描述 投票:2回答:5

我到处寻找将秒转换成hh:mm:ss但找不到合适的

我创建了一个程序,允许用户输入两个不同的时间,然后计算差异

输入的时间分为hh * 3600 - mm * 60 - ss然后转换为秒并相互减去以秒为单位计算差异

例如12:12:12和13:13:13会给我3661秒,但我不知道如何将差异转换回hh:mm:ss

任何帮助,将不胜感激

java
5个回答
4
投票

使用旧的java date api(不推荐,请参阅注释):

int sec = .... //
Date d = new Date(sec * 1000L);
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); // HH for 0-23
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String time = df.format(d);

另见SimpleDateFormat

注意:根据注释,如果秒数超过一天中的秒数(86400),则无法按预期工作。在这种情况下,必须采取不同的方法。

编辑:如果你正在使用JDK 8你可以写:

int sec = ...
Duration duration = Duration.ofSeconds(sec);

这个持续时间对象更能代表您所谈论的内容。我试图找出如何格式化它,但我到目前为止没有运气。

编辑2:在JDK 8之前,您可以使用Joda API

int sec = ...
Period period = new Period(sec * 1000L);
String time = PeriodFormat.getDefault().print(period); // you can customize the format if this one doesn't cut it

这可能是最优雅的解决方案。另见this

编辑3:根据评论,我明确添加了时区。


7
投票

万一你要为此编写自己的算法:

假设我们有1000秒。

我们知道一小时内有3600秒,所以当我们将这个时间格式化为hh:mm:ss时,hh字段将为00.现在假设我们的时间为3700秒。此时间间隔略大于1小时,因此我们知道hh字段将显示01。

因此,要计算hh字段的数量,只需将提供的秒数除以3600。

int hours = seconds / 3600

请注意,当我们有一个大于3600的秒数时,结果会被截断,所以我们留给小时的整数。

继续前往mm领域。再说一次,我们假设我们的时间间隔是3700秒。我们已经知道3700秒略超过1小时 - 我们已经在hour字段中存储了小时数。要计算分钟数,我们将从提供的秒输入中减去3600小时的时间:

int minutes = (seconds - hours * 3600) / 60

因此,如果我们提供3700秒的时间,上面的代码转换为(3700 - 3600)/ 60 - 我们除以60,因为我们想要从秒转换为分钟。

最后,ss字段。我们使用与上面类似的技术来计算秒数。

int seconds = (seconds - hours * 3600) - minutes * 60

public static String formatSeconds(int timeInSeconds)
{
    int hours = timeInSeconds / 3600;
    int secondsLeft = timeInSeconds - hours * 3600;
    int minutes = secondsLeft / 60;
    int seconds = secondsLeft - minutes * 60;

    String formattedTime = "";
    if (hours < 10)
        formattedTime += "0";
    formattedTime += hours + ":";

    if (minutes < 10)
        formattedTime += "0";
    formattedTime += minutes + ":";

    if (seconds < 10)
        formattedTime += "0";
    formattedTime += seconds ;

    return formattedTime;
}

1
投票

这是一种较短的方法:

public static String formatSeconds(int timeInSeconds){
    int secondsLeft = timeInSeconds % 3600 % 60;
    int minutes = Math.floor(timeInSeconds % 3600 / 60);
    int hours = Math.floor(timeInSeconds / 3600);

    string HH = hours < 10 ? "0" + hours : hours;
    string MM = minutes < 10 ? "0" + minutes : minutes;
    string SS = secondsLeft < 10 ? "0" + secondsLeft : secondsLeft;

    return HH + ":" + MM + ":" + SS;
}

1
投票
    public static void formatSeconds(Integer result){

      System.out.print(String.format("%02d",result/3600)+":");
      System.out.print(String.format("%02d",result/60%60)+":");
      System.out.println(String.format("%02d",result%60));

     }

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.