Java Regex Time Validate parseTime(String t)

Here you can find the source of parseTime(String t)

Description

parse Time

License

Open Source License

Declaration

public static long parseTime(String t) throws Exception 

Method Source Code

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

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static long parseTime(String t) throws Exception {
        try {//ww w  .  j  a  v  a2s.  c o m
            if (!t.matches("[0-9]+d[a-z]*"))
                return Math.round(Double.parseDouble(t) * 60) * 1000;
            else {
                Pattern dayPattern = Pattern.compile("([0-9]+)d[a-z]*", Pattern.CASE_INSENSITIVE);
                Matcher m = dayPattern.matcher(t);

                if (m.matches()) {
                    return Integer.parseInt(m.group(1)) * 24 * 60 * 60 * 1000;
                }
            }
        } catch (NumberFormatException e) {
            Pattern hourPattern = Pattern.compile("([0-9]+)h[a-z]*", Pattern.CASE_INSENSITIVE);
            Pattern minPattern = Pattern.compile("([0-9]+)m[a-z]*", Pattern.CASE_INSENSITIVE);
            Pattern secPattern = Pattern.compile("([0-9]+)s[a-z]*", Pattern.CASE_INSENSITIVE);

            Matcher m = hourPattern.matcher(t);

            if (m.matches()) {
                return Integer.parseInt(m.group(1)) * 60 * 60 * 1000;
            }

            m = minPattern.matcher(t);

            if (m.matches()) {
                return Integer.parseInt(m.group(1)) * 60 * 1000;
            }

            m = secPattern.matcher(t);

            if (m.matches()) {
                return Integer.parseInt(m.group(1)) * 1000;
            }
        }
        throw new Exception("badtime");
    }
}

Related

  1. parseTime(String s)
  2. parseTime(String str)
  3. parseTime(String value)
  4. parseTimeDifference(String input)
  5. parseTimeOffset(String s)
  6. parseTimePeriod(String period)