Java How to get just HH:mm:ss from Date

12,186

Solution 1

A Java Date is an instant in time, and does not preserve your expected output format. For that, you need to use a DateFormat. For example,

System.out.println("swSpinnerTimeValue: " + new SimpleDateFormat("HH:mm:ss")
    .format(swSpinnerTimeValue));

Solution 2

tl;dr

The Question and other Answer use troublesome old date-time classes, now legacy, supplanted by the java.time classes.

Duration.between( 
    instantThen ,
    Instant.now().truncatedTo( ChronoUnit.SECONDS )
)

…and…

String.format( 
    "%02d:%02d:%02d", 
    duration.toHoursPart() , 
    duration.toMinutesPart() , 
    duration.toSecondsPart() 
)

Using java.time

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now() ;

You seem to care only about whole seconds. So we can lop off any fractional second.

Instant instant = Instant.now().truncatedTo( ChronoUnit.SECONDS ) ;

To represent a span of time unattached to the timeline with a granularity of hours-minutes-seconds, use the Duration class.

Duration duration = Duration.between( then , instant ) ;

You can generate a string representing that span of time as text in standard ISO 8601 format PTxHxMxS where the P marks the beginning, the T separates any years-months-days from our hours-minutes-seconds. So an hour and a half is PT1H30M.

String output = duration.toString();

To get your clock-style display, create your own string. To get each part, the hours, minutes, and seconds, you will have to do your own math similar to that seen in your Question in Java 8. In Java 9 and later, you may call the to…Part methods.

int hours = duration.toHoursPart() ;
int minutes = duration.toMinutesPart() ;
int seconds = duration.toSeconds() ;

String output = String.format("%02d:%02d:%02d", hours , minutes , seconds ) ;
Share:
12,186

Related videos on Youtube

David Campbell
Author by

David Campbell

HTML CSS Some javascript Some php Dabbled with C, C++, Objective-C Currently dabbling with JAVA and enjoying it. Your help is much appreciated.

Updated on June 04, 2022

Comments

  • David Campbell
    David Campbell almost 2 years

    For my first Java application, I am making a stopwatch. The stopwatch displays time past as hours, minutes and seconds. Like so 00:00:00.

    I wish to display an Alarm (Alert box, whatever) once a certain amount of time (user defined) has past.

    Here is the code that generates the stopwatch display (ignore the deciseconds, we wont concern ourselves with that for the alarm):

        swChronometer = new Timer(10, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int decisec = (int)(System.currentTimeMillis() - swWatchStart) / 10; // 10 x millisecond
                int seconds = decisec / 100;
                int days = seconds / 86400; // 86400 seconds in a day
                int hours = (seconds / 3600) - (days * 24); // 3600 seconds in a hour
                int min = (seconds / 60) - (days * 1440) - (hours * 60); // 60 seconds in a min
                int sec = seconds % 60;
                int decis = decisec % 100;
    
                //------------------------------------------------------- format the ints
                DecimalFormat formatter = new DecimalFormat("00");
                String hoursFormatted = formatter.format(hours);
                String minFormatted = formatter.format(min);
                String secFormatted = formatter.format(sec);
                String decisFormatted = formatter.format(decis);
    
                //------------------------------------------------------- update display
                String s = new String(""+hoursFormatted+":"+minFormatted+":"+secFormatted+"");
                String sDs = new String(decisFormatted);
                swDisplayTimeLabel.setText(s);
                swDisplayDeciseconds.setText(sDs);
            }        
        });
    

    As you can see the Timer ints are eventually converted to strings and then displayed.

    There are radio buttons for After and Every - So an alarm after n amount of time, or every n amount of time.

    I have a JSpinner so the user can define the n time, that is formatted to show only 00:00:00:

        // ----------------------------------
        // set spinner format
        // ----------------------------------
        // inital date at 12pm 00:00:00
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 24); // 24 == 12 PM == 00:00:00
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
    
        swSpinnerTime.setValue(calendar.getTime());
    
        // format field
        JSpinner.DateEditor editor = new JSpinner.DateEditor(swSpinnerTime, "HH : mm : ss");           
        DateFormatter formatter = (DateFormatter)editor.getTextField().getFormatter();
        formatter.setAllowsInvalid(false); // sets it so user cant edit colon
        formatter.setOverwriteMode(true);
    
        swSpinnerTime.setEditor(editor);
    

    There is also a combobox so the user can select what type of alarm.

    Whenever any of these inputs is acted on by the user my function is called to deal with it:

    private void swAlarmSettings() {
        //------------------------------------------------------- which radio is selected
        String swRadioText = "";
    
        if(swRadioAfter.isSelected()) {
            swRadioText = swRadioAfter.getText();
        }
    
        if(swRadioEvery.isSelected()) {
            swRadioText = swRadioEvery.getText();
        }
    
        // debug
        System.out.println("Radio Selected: " +swRadioText);
    
        //------------------------------------------------------- which time is selected     
        Date swSpinnerTimeValue;  
        swSpinnerTimeValue = (Date)swSpinnerTime.getValue();
    
        // debug
        System.out.println("swSpinnerTimeValue: " +swSpinnerTimeValue);
    
        //------------------------------------------------------- which alarm is selected
        String swDropDownSelected = (String)swDropDown.getSelectedItem();
    
        // debug
        System.out.println("swDropDownSelected: " +swDropDownSelected);       
    }
    

    However whenever this function is called it prints out the date as:

       swSpinnerTimeValue: Tue Oct 14 00:00:00 BST 2014
    

    So this is where I'm stuck on how to proceed. I wasn't expecting the whole date (even though its wrong(today is the 13th Oct, not the 14th)) to be displayed when I already formatted it in the JSpinner.

    So I'm presuming I need to parse this value somehow, strip out the data I don't need so I'm left with just HH:mm:ss and then convert it to strings, so that I may compare it to my stopwatch display (String swDisplayTimeLabel) and then fire the alarm once they match.

    I hope I've made my query clear and provided enough info. Thanks for any help.

    I'm working in Netbeans and using the Swing design section to create my application.