Java: Converting an input of seconds into hours/minutes/seconds

后端 未结 2 1620
生来不讨喜
生来不讨喜 2021-01-27 06:01

This is an exercise question taken from Java Software Solutions: foundations of program design by Lewis & Loftus, 4th edition ; Question PP2.6 (here is a link)

相关标签:
2条回答
  • 2021-01-27 06:17

    Here is a much simpler way of doing it:

    public static void main (String[] args) throws Exception {
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        System.out.println(sf.format(new Date(9999000)));
    }
    

    Note: Please note that this will only show the output in 24-hour format and if number of hours is greater than 24 then it'll increment a day and will start over. For example, 30 hours will be displayed as 06:xx:xx. Also, you'll have to pass the input in milliseconds instead of seconds.

    If you want to do it your way then you should probably do something like this:

    public static void main (String[] args) throws Exception {
        long input = 9999;
        long hours = (input - input%3600)/3600;
        long minutes = (input%3600 - input%3600%60)/60;
        long seconds = input%3600%60;
        System.out.println("Hours: " + hours + " Minutes: " + minutes + " Seconds: " + seconds);
    }
    

    Output:

    Hours: 2 Minutes: 46 Seconds: 39
    
    0 讨论(0)
  • 2021-01-27 06:21

    As an alternative of user2004685's answer;

    int seconds = 9999; 
    int hour = 9999 / (60 * 60); //int variables holds only integer so hour will be 2
    seconds = 9999 % (60 * 60); // use modulo to take seconds without hours so it will be 2799
    int minute = seconds / 60; //same as int variable so minute will be 49
    seconds = seconds % 60; // modulo again to take only seconds
    System.out.println(hour + ":" + minute + ":" + seconds);
    
    0 讨论(0)
提交回复
热议问题