Search code examples
javaswingtimeformatjlabel

What is the most efficient way to convert long to HH:mm:ss and display it in a label?


I'm wanting to have my JLabel display values in the format of HH:mm:ss without making use of any external libraries. (the label will update every second)

So for example, the following input in seconds and the desired output are below:

Seconds:                             Output: 
--------------------------------------------------
long seconds = 0                    00:00:00
long seconds = 5                    00:00:05
long seconds = 500                  00:08:20
long seconds = 5000                 01:23:20

Note: the seconds value is of type long



I'm aware that typically one would just do the following conversions to get the desired numbers:

long s = 5000;              //total seconds 

long hrs = (s / 3600)       //hours
long mins = ((s%3600)/60)   //minutes
long secs = (s%60)          //seconds



However, this leaves decimals on the values. Perhaps there is some sort of formatting that will allow me to toss the un-needed decimals.

Options I have come across were String.format(), SimpleDateFormat(), or concatenating a string myself.

The thing is, I will be updating this JLabel every second and sometimes it can count to the equivalent of 5-6 days if not longer.

So I'm looking for someone who has more experience in the area than I, and knows the most efficient way to tackle this issue.


Solution

  • If you don't want to use a formatter class, you can get your work done by using basic operations like conversion among wrapper classes and String operations. Take a look at this code:

    long h, m, s; // Initialize them after calculation.
    String h1, m1, s1;
    
    h1 = Long.toString( h );
    m1 = Long.toString( m );
    s1 = Long.toString( s );
    
    if ( s1.length() < 2 )
        s1 = "0" + s1;
    if ( m1.length() < 2 )
        m1 = "0" + m1;
    if ( h1.length() < 2 )
        h1 = "0" + h1;
    
    String output = h1+":"+m1+":"+s1;
    

    Supposing you have correctly calculated values of seconds, minutes and hours, you can gather String versions of these variables, then format them with a simple length check and finally concatenate these time unit parts.