Java 将秒转换为小时、分钟和秒?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24590769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 13:17:04  来源:igfitidea点击:

converting seconds to hours,minutes, and seconds?

java

提问by user3788063

so Im trying to make a program that can convert s from input into h, m and s. my code so far looks like this:

所以我试图制作一个可以将 s 从输入转换为 h、m 和 s 的程序。到目前为止,我的代码如下所示:

import java.util.Scanner;

class q2_5{
  public static void main(String args[]){

    Scanner input = new Scanner(System.in);
    int s=0;//seconds
    int m=0;//minutes
    int h=0;//hour
    System.out.println("how many seconds?");
    s=input.nextInt();
    if(s >= 60){
      m=s/60;
    } if(m>=60){
      h=m/60;
    }
    System.out.println(s + "s = " + h + " h " + m + " m " + s + "s ");
  }
}

ok so I had to initialize s,m,h to 0 cuz if not I was getting problems in the if statement, so I just put it to 0, since I can change it later :) ok. so the problem with this program right now is that if I type in 3603 I get this output: 3603s = 1 h 60 m 3603s, if I type in 3600 I get this: 3600s = 1 h 60 m 3600s, but the output should have been 3603s = 1h 0m 3s and 3600s = 1h 0m 0s respectively. any tips/advice/solutions on how to solve this problem? :D thanks in advance!

好的,所以我必须将 s,m,h 初始化为 0 因为如果不是我在 if 语句中遇到问题,所以我只是将它设置为 0,因为我以后可以更改它:) 好的。所以这个程序现在的问题是,如果我输入 3603 我得到这个输出:3603s = 1 h 60 m 3603s,如果我输入 3600 我得到这个:3600s = 1 h 60 m 3600s,但输出应该有分别为 3603s = 1h 0m 3s 和 3600s = 1h 0m 0s。关于如何解决这个问题的任何提示/建议/解决方案?:D 提前致谢!

采纳答案by drum

You never changed the value of s. A quick work around would be s = s - (h*3600 + m*60)

您从未更改 的值s。一个快速的解决方法是s = s - (h*3600 + m*60)

EDIT: t = s - (h*3600 + m*60)

编辑: t = s - (h*3600 + m*60)

回答by Kyranstar

Try subtracting from the first term every time you set a lower term.

每次设置较低的项时,请尝试从第一项中减去。

class Test{
  public static void main(String args[]){

    Scanner input = new Scanner(System.in);
    int s=0;//seconds
    int m=0;//minutes
    int h=0;//hour
    System.out.println("how many seconds?");
    s=input.nextInt();
    if(s >= 60){
      m=s/60;
      s = s- m*60;
    } if(m>=60){
      h=m/60;
      m = m - h*60;
    }
    System.out.println(s + "s = " + h + " h " + m + " m " + s + "s ");
  }
}

Just by the way, too, remember to close your inputscanner! Like so : input.close()near the end of the program.

顺便说一句,也请记住关闭您的input扫描仪!像这样:input.close()接近程序的结尾。

回答by jcaron

You can do it all in a single line:

您可以在一行中完成所有操作:

System.out.println((s/3600) + ' hours ' + ((s/60)%60) + ' minutes ' + (s%60) + ' seconds');

回答by Yagel

use this code:

使用此代码:

import java.util.Scanner;
class q2_5{
public static void main(String args[]){

Scanner input = new Scanner(System.in);
int s=0;//seconds
int m=0;//minutes
int h=0;//hour
int s_input=0;
System.out.println("how many seconds?");
s_input=input.nextInt();
s=s_input%60;
if(s >= 60){

m=s_input/60;
}if(m>=60){

h=m/60;
m=m%60;
}
System.out.println(s + "s = " + h + " h " + m + " m " + s + "s ");
 }
}

回答by High Zedd

You should try this

你应该试试这个

import java.util.Scanner;
public class Time_converter {


    public static void main(String[] args) 
    {

        Scanner input = new Scanner (System.in);
        int seconds;
        int minutes ;
        int hours;
        System.out.print("Enter the number of seconds : ");
        seconds = input.nextInt();
        hours = seconds / 3600;
        minutes = (seconds%3600)/60;
        int seconds_output = (seconds% 3600)%60;


        System.out.println("The time entered in hours,minutes and seconds is:");
        System.out.println(hours  + " hours :" + minutes + " minutes:" + seconds_output +" seconds"); 
    }

}

回答by Shohan Ahmed Sijan

My solution is:

我的解决办法是:

 String secToTime(int sec) {
    int second = sec % 60;
    int minute = sec / 60;
    if (minute >= 60) {
        int hour = minute / 60;
        minute %= 60;
        return hour + ":" + (minute < 10 ? "0" + minute : minute) + ":" + (second < 10 ? "0" + second : second);
    }
    return minute + ":" + (second < 10 ? "0" + second : second);
}

回答by Felipe Martins Melo

Java 8 brings a great API for date and time manipulation.

Java 8 为日期和时间操作带来了很棒的 AP​​I。

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class Converter {

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");

    public String convert(int seconds) {
        LocalTime time = LocalTime.MIN.plusSeconds(seconds).toLocalTime();

        return formatter.format(time);
    }
}

Basically, this code adds the number of number of seconds to the minimum datetime supported, which, naturally, has HH:mm:ss equals to 00:00:00.

基本上,此代码将秒数添加到支持的最小日期时间,自然地,HH:mm:ss 等于 00:00:00。

As your are interested in the time only, you extract it by calling toLocalTime()and format it as wanted.

由于您只对时间感兴趣,因此您可以通过调用toLocalTime() 来提取它并根据需要对其进行格式化。

回答by Basil Bourque

Obviously you are doing some homework/practice to learn Java. But FYI, in real work you needn't do those calculations and manipulations. There's a class for that.

显然,您正在做一些功课/练习来学习 Java。但是仅供参考,在实际工作中,您不需要进行这些计算和操作。有一个课程。

java.time.Duration

java.time.Duration

For a span of time, use the Durationclass. No need for you to do the math.

在一段时间内,使用Duration该类。您无需进行数学运算。

Duration d = Duration.ofSeconds( s );

The standard ISO 8601format for a string representing a span of time unattached to the timeline is close to your desired output: PnYnMnDTnHnMnSwhere the P marks the beginning and the T separates any years-months-days from any hours-minutes-seconds. So an hour and a half is PT1H30M.

代表未附加到时间线的时间跨度的字符串的标准ISO 8601格式接近您想要的输出:PnYnMnDTnHnMnS其中 P 标记开始,T 将任何年-月-日与任何时-分-秒分开。所以一个半小时是PT1H30M

The java.time classes use the ISO 8601 formats by default when parsing or generating strings.

java.time 类在解析或生成字符串时默认使用 ISO 8601 格式。

String output = d.toString() ;

In Java 9 and later, you can call the to…Partmethods to retrieve the individual parts of hours, minutes, and seconds.

在 Java 9 和更高版本中,您可以调用这些to…Part方法来检索小时、分钟和秒的各个部分。

回答by Kandarp

import java.util.Scanner;

public class Prg2 {

    public static void main(String[] args) {
        int seconds = 0;
        int hours = 0;
        int minutes = 0;
        int secondsDisp = 0;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the number of seconds: ");
        seconds = in.nextInt();
        hours = seconds/3600;
        minutes = (seconds - (hours*3600))/60;
        secondsDisp = ((seconds - (hours*3600)) - (minutes * 60));
        System.out.println(seconds + " seconds equals " + hours + " hours, " + minutes + " minutes and " + secondsDisp + " seconds");
    }
}

回答by Durgesh Pal

class time{
    public static void main (String args[]){
        int duration=1500;
         String testDuration = "";

        if(duration < 60){
            testDuration = duration + " minutes";
        }
        else{

            if((duration / 60)<24)
            {
                if((duration%60)==0){
                    testDuration = (duration / 60) + " hours";
                }
                else{
            testDuration = (duration / 60) + " hours," + (duration%60) + " minutes";
                }
            }
            else{

                if((duration%60)==0){
                    if(((duration/60)%24)==0){
                        testDuration = ((duration / 24)/60) + " days,";

                    }
                    else{
                    testDuration = ((duration / 24)/60) + " days," + (duration/60)%24 +"hours";
                    }
                }
                    else{
                testDuration = ((duration / 24)/60) + " days," + (duration/60)%24 +"hours"+ (duration%60) + " minutes";
                    }
            }
        }

        System.out.println(testDuration);
    }
}