Switch from milliseconds to a time in hours, minutes and seconds in Java

1

I have a variable in String and it is the milliseconds that it takes to get from one point to another. I need to put that value in Hours: Minutes: Seconds format

I am using Java 6 and objects Date , but when I send this value to the database, the result is not as expected.:

String tiempo = "857"; // Es el tiempo en milisegundos
long duration = Long.parseLong(tiempo);
action.setDuration(new Time(duration));

I am using a PostgreSQL 9.3 and the DDL where the table in which I store the value is created

sug_duration time without time zone, -- Time duration

He always returns me 01:00:00, even if the time is shorter

Any ideas that can help me?

    
asked by jjmartinez 10.11.2016 в 15:14
source

1 answer

2

I can do a function that converts the milliseconds. I know that 1000 milliseconds is 1 second, that 60 seconds is a minute, that 60 minutes is an hour.

public static int milisegundos2tiempo(int ms)
{
    int mili = ms%1000; ms -= mili; ms /= 1000;
    int segs = ms%60; ms -= segs; ms /= 60;
    int mins = ms%60; ms -= mins; ms /= 60;
    int horas = ms;
    return horas*1000*100*100 + mins*1000*100 + segs*1000 + mili;
}

It will return a strange half whole, do not worry, I'll explain it to you:

If you return 223344555, it means that they are 22 hours with 33 minutes with 44 seconds and 555 milliseconds ... This can return a number of hours greater than 24 ... In that case, you only have to change int horas = ms; int horas = ms%24; ... It is also recommended some function to convert that strange number to a String and format it with bars or hyphens (/ or -).

Since you need to return a Date , I have decided to investigate, and found a link that explains that. Editing a bit, I have the answer you need.

import java.util.Date;
public class Programa {
    public static void main (String []args){

        System.out.print ("Ingrese la cantidad de milisegundos:\n");
        Scanner teclado = new Scanner(System.in);
        int n = teclado.nextInt();
        teclado.close();

        int res = milisegundos2tiempo(n);
        Date fecha1;
        fecha1 = new Date(100,0,0,res%10000000,res%100000,res%1000);
        System.out.println( fecha1.toGMTString() );
    }
}
    
answered by 10.11.2016 в 15:46