Java Regex Time Validate parseTimePeriod(String s)

Here you can find the source of parseTimePeriod(String s)

Description

Note, right now this just parses the hour/minute/second periods

License

Open Source License

Parameter

Parameter Description
s The date string

Return

The time

Declaration

public static long parseTimePeriod(String s) 

Method Source Code

//package com.java2s;

import java.util.regex.*;

public class Main {
    /**/* w w  w  .  j  a  v  a 2 s  .c o m*/
     * Note, right now this just parses the hour/minute/second periods
     *
     * @param s The date string
     * @return The time
     */
    public static long parseTimePeriod(String s) {
        if (!s.startsWith("P")) {
            throw new IllegalArgumentException("Unknown time period:" + s);
        }
        s = s.substring(1);
        String tmp = "((\\d+)Y)?((\\d+)M)?((\\d+)D)?(T((\\d+)H)?((\\d+)M)?((\\d+)S)?)";
        Pattern pattern = Pattern.compile(tmp);
        Matcher matcher = pattern.matcher(s);
        boolean ok = matcher.find();
        if (!ok) {
            System.err.println("No match:" + s);
            return 0;
        }
        System.err.println("Duration:" + s);
        for (int i = 1; i <= matcher.groupCount(); i++) {
            System.err.println("\t" + matcher.group(i));
        }

        int gidx = 1;
        gidx++;
        long y = convert(str(matcher.group(gidx++), "0"));
        gidx++;
        long m = convert(str(matcher.group(gidx++), "0"));
        gidx++;
        long d = convert(str(matcher.group(gidx++), "0"));
        gidx++;
        gidx++;
        long h = convert(str(matcher.group(gidx++), "0"));
        gidx++;
        long min = convert(str(matcher.group(gidx++), "0"));
        gidx++;
        long sec = convert(str(matcher.group(gidx++), "0"));
        //      System.err.println ("y:" + y + "/" + m+"/"+d+"/" +h+"/"+min+"/"+sec);
        return h * 3600 + m * 60 + sec;
    }

    /**
     * Convert to a long
     *
     * @param s string
     * @return long
     */
    private static long convert(String s) {
        return new Long(s).longValue();
    }

    /**
     * If s1 is null return dflt. Else return s1
     *
     * @param s1   string
     * @param dflt default
     * @return s1 or dflt
     */
    private static String str(String s1, String dflt) {
        return ((s1 != null) ? s1 : dflt);
    }
}

Related

  1. parseTime(String t)
  2. parseTime(String value)
  3. parseTimeDifference(String input)
  4. parseTimeOffset(String s)
  5. parseTimePeriod(String period)
  6. parseTimeSpan(String timeSpan)
  7. parseTimestamp(final String value)
  8. parseTimestamp(String s)
  9. parseTimeString(String str)