Java Regex Time Validate parseTimeString(String str)

Here you can find the source of parseTimeString(String str)

Description

parse Time String

License

Open Source License

Declaration

public static long parseTimeString(String str)
            throws NumberFormatException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static final Pattern TIMESTAMP_PATTERN = Pattern
            .compile("^(\\d?\\d)(?::([0-5]?\\d))?(?::([0-5]?\\d))?$");

    public static long parseTimeString(String str)
            throws NumberFormatException {
        AtomicLong millis = new AtomicLong(0);
        long seconds = 0;
        long minutes = 0;
        long hours = 0;

        Matcher m = TIMESTAMP_PATTERN.matcher(str);

        m.find();// w w w  .  j  a va 2 s .co m

        int capturedGroups = 0;
        if (m.group(1) != null)
            capturedGroups++;
        if (m.group(2) != null)
            capturedGroups++;
        if (m.group(3) != null)
            capturedGroups++;

        switch (capturedGroups) {
        case 0:
            throw new IllegalStateException("Unable to match " + str);
        case 1:
            seconds = Integer.parseInt(m.group(1));
            break;
        case 2:
            minutes = Integer.parseInt(m.group(1));
            seconds = Integer.parseInt(m.group(2));
            break;
        case 3:
            hours = Integer.parseInt(m.group(1));
            minutes = Integer.parseInt(m.group(2));
            seconds = Integer.parseInt(m.group(3));
            break;
        }

        minutes = minutes + hours * 60;
        seconds = seconds + minutes * 60;
        millis.set(seconds * 1000);

        return millis.get();
    }
}

Related

  1. parseTimePeriod(String period)
  2. parseTimePeriod(String s)
  3. parseTimeSpan(String timeSpan)
  4. parseTimestamp(final String value)
  5. parseTimestamp(String s)
  6. parseTimeString(String str, TimeUnit unit)
  7. parseTimeString(String time)