3

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:

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!

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
user3788063
  • 43
  • 1
  • 1
  • 3
  • 1
    Your posted code was all left-justified making it unreadable. I have tried to fix this. In the future, please fix this yourself. If we can't read your code, we can't understand it nor can we help. – Hovercraft Full Of Eels Jul 05 '14 at 21:41

11 Answers11

6

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.time.Duration

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

Duration d = Duration.ofSeconds( s );

The standard ISO 8601 format for a string representing a span of time unattached to the timeline is close to your desired output: PnYnMnDTnHnMnS where 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.

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

String output = d.toString() ;

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


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Note that the `Duration` class requires Android API level 26 or higher: https://developer.android.com/reference/java/time/Duration If you still need it maybe this is a possible workaround: https://stackoverflow.com/a/61218004/1306012 – Bruno Bieri May 29 '21 at 11:59
  • 1
    @BrunoBieri I added the *About java.time* section to address your issue of Android version support. – Basil Bourque May 29 '21 at 22:21
5

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);
}
Shohan Ahmed Sijan
  • 4,391
  • 1
  • 33
  • 39
4

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

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.

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

Felipe Martins Melo
  • 1,323
  • 11
  • 15
  • 1
    Why not shorten that by going straight to `LocalTime` without `LocalDateTime`? `LocalTime.MIN.plusHours( h ).plusMinutes( m ).plusSeconds( s )` – Basil Bourque Apr 11 '17 at 16:27
  • 2
    No need for the `DateTimeFormatter` in this case. The desired output is in standard ISO 8601 format. The java.time classes use ISO 8601 formats by default when parsing and generating strings. `myLocalTime.toString()` So your entire code could be reduced to simply: `LocalTime.MIN.plusHours( h ).plusMinutes( m ).plusSeconds( s ).toString()` No real need for a subroutine. – Basil Bourque Apr 11 '17 at 16:29
  • 1
    @BasilBourque, you're right. I've just updated the code. Regarding the formatter, although the question asks for a specific format, I let it for completeness in case someone else is interested in a different format. – Felipe Martins Melo Apr 11 '17 at 17:07
2

You can do it all in a single line:

System.out.println((s/3600) + ' hours ' + ((s/60)%60) + ' minutes ' + (s%60) + ' seconds');
jcaron
  • 17,302
  • 6
  • 32
  • 46
1

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

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

drum
  • 5,416
  • 7
  • 57
  • 91
0

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 input scanner! Like so : input.close() near the end of the program.

Kyranstar
  • 1,650
  • 2
  • 14
  • 35
0

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"); 
    }

}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
High Zedd
  • 53
  • 10
0
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");
    }
}
Kandarp
  • 893
  • 7
  • 8
0
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);
    }
}
Durgesh Pal
  • 695
  • 5
  • 13
  • This assumes the input is minutes and you will convert it to days:hours:minutes which is not the question. You could easily modify it to address the exact question though. – Pablo Adames Oct 16 '19 at 17:12
0

A simpler solution would be:

T = in.nextInt();

int s = T%60;

int minute = T/60;

int m = minute%60;

int h = minute/60;

return h+"h"+m+"m"+s+"s";
roger_that
  • 9,493
  • 18
  • 66
  • 102
-1

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 ");
 }
}
Yagel
  • 75
  • 1
  • 6