user3397972
user3397972

Reputation: 105

how to convert seconds into hhmmss

i have looked everywhere to convert seconds into hh:mm:ss but couldn't find the right one

i created a program that allows a user to enter two different times and then calculate the difference

the times entered are split in hh * 3600 - mm * 60 - ss then converted into seconds and subtracted from each other to calculate difference in seconds

for example 12:12:12 and 13:13:13 would give me 3661 seconds but i don't know how to convert the difference back into hh:mm:ss

any help would be appreciated

Upvotes: 10

Views: 36950

Answers (7)

AlexGolub
AlexGolub

Reputation: 17

You can use TimeUnit class to easily convert from seconds to hours, minutes and seconds.

import java.util.Scanner;
import java.util.concurrent.TimeUnit;

class Main {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner(System.in)) {
            long seconds = Long.parseLong(sc.nextLine());

            long HH = TimeUnit.SECONDS.toHours(seconds) % 24;
            long MM = TimeUnit.SECONDS.toMinutes(seconds) % 60;
            long SS = TimeUnit.SECONDS.toSeconds(seconds) % 60;

            System.out.printf("%02d:%02d:%02d%n", HH, MM, SS);
        }
    }
}

Upvotes: 2

Mpi314
Mpi314

Reputation: 11

I know it's a bit late to answer the question , but never mind. It's basically the same as BarBar1234 answer, but you can combine it all into a single String:

String.format("%02d:%02d:%02d", seconds / 3600, (seconds / 60) % 60, seconds % 60);

Upvotes: 1

Sebastian Londono
Sebastian Londono

Reputation: 51

This is a shorter method:

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

    String HH = ((hours       < 10) ? "0" : "") + hours;
    String MM = ((minutes     < 10) ? "0" : "") + minutes;
    String SS = ((secondsLeft < 10) ? "0" : "") + secondsLeft;

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

Upvotes: 5

NetIceGear
NetIceGear

Reputation: 252

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

     }

Upvotes: 7

Giovanni Botta
Giovanni Botta

Reputation: 9816

Using the old java date api (not recommended, see comments):

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

See also SimpleDateFormat.

Note: as per comments, if the number of seconds exceeds the number of seconds in a day (86400) that won't work as expected. In that case a different approach must be taken.

EDIT: If you're using JDK 8 you can write:

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

This duration object better represents what you're talking about. I am trying to find out how to format it as you want to but I have had no luck so far.

EDIT 2: prior to JDK 8 you can use the 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

That's probably the most elegant solution. See also this.

EDIT 3: As per comments, I explicitly added the time zone.

Upvotes: 16

isak gilbert
isak gilbert

Reputation: 2611

Use JODA time libary http://joda-time.sourceforge.net/apidocs/index.html

PeriodFormatter formatter = ... // Define your formatting here
Period firstPeriod = new Period(13, 13, 13, 0);
Period secondPeriod = new Period(12, 12, 12, 0);
Period resultPeriod = firstPeriod.minus(secondPeriod);
String formattedPeriod = formatter.print(resultPeriod);

// Display period e.g. System.out.println(formatterPeriod);
// ....

Upvotes: 0

JustSoAmazing
JustSoAmazing

Reputation: 747

Just in case you're looking to write your own algorithm for this:

Let's say we have 1000 seconds.

We know that there're 3600 seconds in an hour, so when we format this time as hh:mm:ss, the hh field will be 00. Now let's say we're given a time of 3700 seconds. This time interval is slightly larger than 1 hour, so we know that the hh field will show 01.

So to calculate the number for the hh field, simply divide the provided seconds amount by 3600.

int hours = seconds / 3600

Note that when we have a seconds amount greater than 3600, the result is truncated, so we're left with an integer amount for the hours.

Moving on to the mm field. Again, let's assume we're given a time interval of 3700 seconds. We already know that 3700 seconds is slightly more than 1 hour - we've stored the number of hours in the hour field. To calculate the number of minutes, we'll subtract the hours times 3600 from the provided seconds input:

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

So if we have a provided time of 3700 seconds, the above code translates to (3700 - 3600) / 60 - we divide by 60 because we want to convert from seconds to minutes.

Finally, the ss field. We use a similar technique as above to calculate the number of seconds.

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

Upvotes: 12

Related Questions