Webman
Webman

Reputation: 1554

How to convert the seconds in this format "HH:mm:ss"

I want to convert the second/milliseconds in this format "HH:mm:ss" (for esamples, from 5 seconds to 00:00:05). I tried to get that format in this way:

int millis = 5000;
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
String time = df.format(millis);

In that way, I get "01:00:05" and not "00:00:05". Where am I wrong?

Upvotes: 35

Views: 62295

Answers (8)

zakaria-alshamere
zakaria-alshamere

Reputation: 53

Show time duration like YouTube

String duration(int length){
    String format =String.format(Locale.US, "%02d:%02d:%02d", length/3600, (length%3600)/60, length%60);
    if (format.length()>=7 && format.startsWith("00:0"))
        format=format.replace("00:0","");
    if (format.length()>=7 && format.startsWith("00:"))
        format=format.replace("00:","");
    Log.d("seeformat",format);
    return format;
}

Upvotes: 0

Bokili Production
Bokili Production

Reputation: 414

This example has no localization warning:

public static String getTime(int sek) {
    return String.format(Locale.US, "%02d:%02d:%02d", sek/3600, (sek%3600)/60, sek%60);
}

Upvotes: 0

xeruf
xeruf

Reputation: 3010

I wrote a simple utility function for this task which does not require any Java version nor instantiates any unnecessary objects:

/**
 * provides a String representation of the given time
 * @return {@code millis} in hh:mm:ss format
 */
public static final String formatTime(long millis) {
    long secs = millis / 1000;
    return String.format("%02d:%02d:%02d", secs / 3600, (secs % 3600) / 60, secs % 60);
}

Unlike some other solutions here, this can even deal with up to 100 hours

Upvotes: 21

Anonymous
Anonymous

Reputation: 86399

Java 9 answer:

    Duration dur = Duration.ofMillis(millis);
    System.out.println(String.format("%02d:%02d:%02d",
                       dur.toHours(), dur.toMinutesPart(), dur.toSecondsPart()));

(not tested yet)

The toXxPart methods are described in the API docs for Java 9.

Upvotes: 1

Andrzej Doyle
Andrzej Doyle

Reputation: 103847

Timezones.

The long value 5000 means 5 seconds after the epoch. For the majority of timezones, 5 seconds after the epoch is not 5 seconds past midnight local time.

Java 8 update:

java.time.LocalTime will handle the idea of a wall-clock "time of day" without you having to worry about the timezones and days implicit in java.util.Date. If you can use Java 8, and your durations will always be less than a day, then a correct version of your example can be as simple as:

int millis = 5000;
int seconds = millis / 1000; // Maybe no need to divide if the input is in seconds
LocalTime timeOfDay = LocalTime.ofSecondOfDay(seconds);
String time = timeOfDay.toString();

(I guess strictly speaking, java.time.Duration is a better model of what you want, in that it represents a certain number of seconds, rather than a time-of-day. But it's a pain to format into hh:mm:ss, so if you're always dealing with sub-24hour values, TimeOfDay gives you this formatting for free and is otherwise equivalent.)


If you're stuck with Java 7 or below, then explicitly specifying a timezone of GMT in your example code should give you the output you expect.

Here's a Scala REPL session demonstrating the problem, and Java 7 solution, on my machine:

scala> val millis = 5000
millis: Int = 5000

scala> val df = new java.text.SimpleDateFormat("HH:mm:ss")
df: java.text.SimpleDateFormat = java.text.SimpleDateFormat@8140d380

scala> df.format(millis)
res0: java.lang.String = 01:00:05

scala> df.getTimeZone.getID
res1: java.lang.String = GB

scala> df.getTimeZone.getOffset(millis)
res2: Int = 3600000

scala> df.setTimeZone(java.util.TimeZone.getTimeZone("GMT"))

scala> df.format(millis)
res3: java.lang.String = 00:00:05

So you can see that my default time zone is GB, which has a 1 hour offset from GMT at the time denoted by 5000L. Setting the timezone to GMT gievs the expected output of 00:00:05.

Upvotes: 24

localhost
localhost

Reputation: 5598

You should get SimpleDateFormat with Locale argument.

public static String getDateFromMillis(long millis) {
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
    return formatter.format(new Date(millis));
}

Upvotes: 5

maxim delaet
maxim delaet

Reputation: 21

public class HHMMSS {

        final int UUR = 3600;
        final int MINUUT = 60;

    public void converteerTijd() {

        int uren, minuten, seconden, ingave;
        System.out.print("Geef een aantal seconden: ");
        ingave = Input.readInt();
        uren = ingave / UUR;
        minuten = (ingave - uren * UUR) / MINUUT;
        seconden = ingave - uren * UUR - minuten * MINUUT;
        String nU1 = (uren < 10) ? "0" : "";
        String nM1 = (minuten < 10) ? "0" : "";
        String nS1 = (seconden < 10) ? "0" : "";
        System.out.println(nU1 + uren + "-" + nM1 + minuten + "-" + nS1 + seconden);

Upvotes: 1

B. Anderson
B. Anderson

Reputation: 3179

I got this to work. Let me know if it works for you. Seems like a lot of lines to do something seemingly simple..

    int millis = 5000;
    TimeZone tz = TimeZone.getTimeZone("UTC");
    SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
    df.setTimeZone(tz);
    String time = df.format(new Date(millis));
    System.out.println(time);

Upvotes: 16

Related Questions