Search code examples
javadatedate-formattinghour

Formatting hour in java 20h 10m 5000s to 20h 10m 10s


I am trying to create a small program that we give a wrong time for example: 20h 10m 5000s and that transforms it giving me back 20h 10m 50s. But I am unable to show you the code to see if you can help me, thank you very much :)

import java.util.Date;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;

public class EejercicioBasico3 {
    public static void main(String[] args) {
        
        Date date = new Date();
        SimpleDateFormat dateForm = new SimpleDateFormat("HH:mm:ss");
 
        String UserDate = dateForm.format(JOptionPane.showInputDialog("Escriba una hora en formato hh-mm-ss"));
        
        System.out.println(date);
        System.out.println(UserDate);
    
    }
}

Solution

  • Removing excess digits

    I tend to understand from your question and comments that you are assuming that the user may type too many digits by mistake. I am further assuming that each number may be in the interval from 0 or 00 to 59, and any digits that make the number greater than 59 or wider than two digits are to be removed. It’s probably not perfect, but may get you started.

        String inputTimeString = "20h 10m 5000s";
        String outputTimeString
                = inputTimeString.replaceAll("([6-9]|[0-5]\\d)\\d+", "$1");
        System.out.println(outputTimeString);
    

    Output is:

    20h 10m 50s

    The regular expression first matches either a digit in the range 6 – 9 or two digits starting with 0 through 5 to ensure that we got at most 59. This or these digits are captured as a group using round brackets around the group in the regexp. After the group any number of excess digits is matched. In the replacement string I use $1 to denote that the digits should be replaced with just what was matched in capturing group no. 1 (the only capturing group in this case).

    Try another example:

        String inputTimeString = "60h 010m 777s";
    

    6h 01m 7s

    Reservation: If this is a basic exercise from school, your teacher may have another solution in mind, but you can judge that better. If you haven’t learnt regular expressions, you probably should not hand in a solution that uses them. Maybe you were expected to iterate through the input string and add characters that are OK to a string buffer where you collect your output.

    Converting excess seconds to minutes and hours

    If instead you want excess seconds — over 59 seconds — converted to minutes and hours, use the Duration class:

        String isoTimeString = "PT" + inputTimeString.replaceAll(" ", "");
        Duration dur = Duration.parse(isoTimeString);
        String outputTimeString = String.format("%dh %dm %ds",
                dur.toHours(), dur.toMinutesPart(), dur.toSecondsPart());
        
        System.out.println(outputTimeString);
    

    21h 33m 20s

    Duration.parse() requires ISO 8601 format. This is obtained from your format by prefixing PT (think period of time) and removing the spaces. The String.format() call reproduces your format.

    Always avoid Date and SimpleDateFormat

    The classes you were trying to use, SimpleDateFormat and Date, are poorly designed and long outdated and were never meant for a job like this. I recommmend that you never use them and always use java.time, the modern Java date and time API, for your time work. The Duration class is part of java.time.

    Links