User Tools

Site Tools


java:durationtotext

Convert a time duration into a text

Output in Spanish. I think it would be translatable easily.

durationToText ->  21 minutos y 57,432 segundos
durationToText -> 3 días, 14 horas, 19 minutos y 0,516 segundos
    private String durationToText( long start, long end )
    {
        NumberFormat format = new DecimalFormat( "###" );
        NumberFormat formatSeconds = new DecimalFormat( "##.###" ); 
        long milliseconds = end - start; 
        long months;
        long modMonths;
        long days; 
        long modDays;
        long hours; 
        long modHours;
        long minutes; 
        long modMinutes;
        float seconds; 
 
        months = milliseconds / (30L*24L*3600L*1000L);
        modMonths = milliseconds % (30L*24L*3600L*1000L);
        days = modMonths / (24L*3600L*1000L);
        modDays = modMonths % (24L*3600L*1000L);
        hours = modDays / (3600L*1000L);
        modHours = modDays % (3600L*1000L);
        minutes = modHours / (60L*1000L);
        modMinutes = modHours % (60L*1000L);
        seconds = (float) modMinutes / (float) 1000;
 
        String out; 
 
        out = "";
        if( months != 0 ) 
            out +=  format.format(months) + " meses"; 
        if( days != 0 )
        {
            // add a comma or a conjunction (y)
            if( !out.isEmpty() )
            {
                // if the rest of elements are zero, add a "y " 
                if( hours == 0 && minutes == 0 && seconds == 0 ) 
                    out += " y ";
                else
                    out += ", "; 
            }
            out += format.format(days) + " días";
        } // days != 0 
        if( hours != 0 )
        {
            // add a comma or a conjunction 
            if( !out.isEmpty() )
            {
                // if the rest of elements are zero, add a "y "
                if( minutes == 0 && seconds == 0 ) 
                    out += " y ";
                else
                    out += ", ";
            }
            out += format.format(hours) + " horas"; 
        } // hours != 0 
        if( minutes != 0 )
        {
            // add a comma or a conjunction 
            if( !out.isEmpty() )
            {
                // if the rest of elements are zero, add a "y"
                if( seconds == 0 )
                    out += " y "; 
                else
                    out += ", "; 
            }
            out += format.format(minutes) + " minutos"; 
        } // minutes != 0 
        if( seconds != 0 )
        {
            // just add a "y" - copulative conjunction
            if( !out.isEmpty() )
            {
                out += " y "; 
            }
            out += formatSeconds.format(seconds) + " segundos";
        }
 
        return out;
    }
java/durationtotext.txt · Last modified: 2014/12/24 10:42 (external edit)