Jun 052011
 

A very tolerant time string parser.

package sactosoft.common;

public class MilitaryTimeParser {
    String timeString;

    String hh = "00";

    String mm = "00";

    String ss = "00";

    private boolean isValid = true;

    public MilitaryTimeParser() {
    }

    public MilitaryTimeParser(String timeString) {
        this.setTimeString(timeString);
    }

    public void setTimeString(String timeString) {
        this.timeString = timeString;
        parseTime();
    }

    public String getTimeString() {
        return this.hh + this.mm + this.ss;
    }

    public String getTimeString(String dlm) {
        return this.hh + dlm + this.mm + dlm + this.ss;
    }

    private void parseTime() {
        // the extrac 00 guard against the case when the user enter 8 digits
        String[] tt = { "00", "00", "00", "00" };
        String t = this.timeString.replaceAll("[^0-9]", " ").trim().replaceAll(" +", " ").replaceAll("[^0-9]", ":");
        if (t.contains(":")) {
            for (int i = 0; i < t.split(":").length; i++) {
                tt[i] = t.split(":")[i];
                tt[i] = "0".substring(tt[i].length() - 1) + tt[i];
            }
        } else {
            int timeLen = t.length();
            // pad the string to even number of digits
            String pad = "0".substring(0, timeLen - (timeLen / 2) * 2);
            t = pad + t;
            timeLen = t.length();
            for (int i = 0; i < t.length() / 2; i++) {
                tt[i] = t.substring(i * 2, (i + 1) * 2);
            }
        }

        this.hh = tt[0];
        this.mm = tt[1];
        this.ss = tt[2];
        if ((Integer.parseInt(this.hh) > 24) || (Integer.parseInt(this.mm) > 59) || (Integer.parseInt(this.ss) > 59)) {
            this.isValid = false;
        }
    }

    public boolean isValidTime() {
        return this.isValid;
    }

    /**
     * @return the hh
     */
    public String getHH() {
        return this.hh;
    }

    /**
     * @return the mm
     */
    public String getMM() {
        return this.mm;
    }

    /**
     * @return the ss
     */
    public String getSS() {
        return this.ss;
    }
}