[java] Java: convert seconds to minutes, hours and days

"The output should look like this (it is a good idea to echo back the input): You entered 500,000 seconds, which is 5 days, 18 hours, 53 minutes and 20 seconds. (5 days 18:53:20 hours)

So can you guys tell me how I should do it, what is the easiest way to understand and do it, please help guys, I'm really stuck, also he said "no hard coding" which I'm not exactly sure what it is but I think he wants us to assign them constants.

This question is related to java

The answer is


An example using built in TimeUnit.

long uptime = System.currentTimeMillis();

long days = TimeUnit.MILLISECONDS
    .toDays(uptime);
uptime -= TimeUnit.DAYS.toMillis(days);

long hours = TimeUnit.MILLISECONDS
    .toHours(uptime);
uptime -= TimeUnit.HOURS.toMillis(hours);

long minutes = TimeUnit.MILLISECONDS
    .toMinutes(uptime);
uptime -= TimeUnit.MINUTES.toMillis(minutes);

long seconds = TimeUnit.MILLISECONDS
    .toSeconds(uptime);

Thanks guys for all the help, I really appreciate but I actually did some thinking and start doing some pseudo code and came up with this.

import java.util.Scanner;

public class Project {

public static void main(String[] args) {



//variable declaration  
Scanner scan = new Scanner(System.in);
final int MIN = 60, HRS = 3600, DYS = 84600;
int input, days, seconds, minutes, hours, rDays, rHours;

//input 
System.out.println("Enter amount of seconds!");
input = scan.nextInt();


//calculations
days = input/DYS;
rDays = input%DYS;
hours = rDays/HRS;
rHours = rDays%HRS;
minutes = rHours/MIN;
seconds = rHours%MIN;

//output
if (input >= DYS) {
    System.out.println(input + " seconds equals to " + days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
}

else if (input >= HRS && input < DYS) {
    System.out.println(input + " seconds equals to " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
}

else if (input >= MIN && input < HRS) {
    System.out.println(input + " seconds equals to " + minutes + " minutes " + seconds + " seconds");
}

else if (input < MIN) {
    System.out.println(input + " seconds equals to seconds");
}

scan.close();


}   

I know it looks really noobie but keep in mind I'm still new not just Java but programming entirely, and who knew pseudo code was actually really helpful.


You can use the Java enum TimeUnit to perform your math and avoid any hard coded values. Then we can use String.format(String, Object...) and a pair of StringBuilder(s) as well as a DecimalFormat to build the requested output. Something like,

Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number of seconds:");
String str = scanner.nextLine().replace("\\,", "").trim();
long secondsIn = Long.parseLong(str);
long dayCount = TimeUnit.SECONDS.toDays(secondsIn);
long secondsCount = secondsIn - TimeUnit.DAYS.toSeconds(dayCount);
long hourCount = TimeUnit.SECONDS.toHours(secondsCount);
secondsCount -= TimeUnit.HOURS.toSeconds(hourCount);
long minutesCount = TimeUnit.SECONDS.toMinutes(secondsCount);
secondsCount -= TimeUnit.MINUTES.toSeconds(minutesCount);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%d %s, ", dayCount, (dayCount == 1) ? "day"
        : "days"));
StringBuilder sb2 = new StringBuilder();
sb2.append(sb.toString());
sb2.append(String.format("%02d:%02d:%02d %s", hourCount, minutesCount,
        secondsCount, (hourCount == 1) ? "hour" : "hours"));
sb.append(String.format("%d %s, ", hourCount, (hourCount == 1) ? "hour"
        : "hours"));
sb.append(String.format("%d %s and ", minutesCount,
        (minutesCount == 1) ? "minute" : "minutes"));
sb.append(String.format("%d %s.", secondsCount,
        (secondsCount == 1) ? "second" : "seconds"));
System.out.printf("You entered %s seconds, which is %s (%s)%n",
        new DecimalFormat("#,###").format(secondsIn), sb, sb2);

Which, when I enter 500000 outputs the requested (manual line break added for post) -

You entered 500,000 seconds, which is 5 days, 18 hours, 
53 minutes and 20 seconds. (5 days, 18:53:20 hours)

It should be like:

    public static void calculateTime(long seconds) {
            int day = (int)TimeUnit.SECONDS.toDays(seconds);        
            long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
            long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
            long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);

            System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);

        }

Explanation:

TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours with out consideration for days. Minus the hours for days you already got i.e, day*24. You now got remaining hours. Same for minute and second. You need to minus the already got hour and minutes respectively.


Have a look at the class

org.joda.time.DateTime

This allows you to do things like:

old = new DateTime();
new = old.plusSeconds(500000);
System.out.println("Hours: " + (new.Hours() - old.Hours()));

However, your solution probably can be simpler:

You need to work out how many seconds in a day, divide your input by the result to get the days, and subtract it from the input to keep the remainder. You then need to work out how many hours in the remainder, followed by the minutes, and the final remainder is the seconds.

This is the analysis done for you, now you can focus on the code.

You need to ask what s/he means by "no hard coding", generally it means pass parameters, rather than fixing the input values. There are many ways to do this, depending on how you run your code. Properties are a common way in java.


The simpliest way

    Scanner in = new Scanner(System.in);
    System.out.println("Enter seconds");
    int s = in.nextInt();

    int sec = s % 60;
    int min = (s / 60)%60;
    int hours = (s/60)/60;

    System.out.println(hours + ":" + min + ":" + sec);

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

}

my quick answer with basic java arithmetic calculation is this:

First consider the following values:

1 Minute = 60 Seconds
1 Hour = 3600 Seconds ( 60 * 60 )
1 Day = 86400 Second ( 24 * 3600 )
  1. First divide the input by 86400, if you you can get a number greater than 0 , this is the number of days. 2.Again divide the remained number you get from the first calculation by 3600, this will give you the number of hours
  2. Then divide the remainder of your second calculation by 60 which is the number of Minutes
  3. Finally the remained number from your third calculation is the number of seconds

the code snippet is as follows:

int input=500000;
int numberOfDays;
int numberOfHours;
int numberOfMinutes;
int numberOfSeconds;

numberOfDays = input / 86400;
numberOfHours = (input % 86400 ) / 3600 ;
numberOfMinutes = ((input % 86400 ) % 3600 ) / 60 
numberOfSeconds = ((input % 86400 ) % 3600 ) % 60  ;

I hope to be helpful to you.