Java Regex Time Validate parseTimeSpan(String timeSpan)

Here you can find the source of parseTimeSpan(String timeSpan)

Description

Parse a time span that's in minutes by defualt.

License

Open Source License

Declaration

public static long parseTimeSpan(String timeSpan) 

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 {
    /**/*from w ww . j a  va 2s . c om*/
     * Parse a time span that's in minutes by defualt.
     *
     * Return number of seconds.
     */
    public static long parseTimeSpan(String timeSpan) {
        Pattern hourRegex = Pattern.compile("(\\d+)h");
        Pattern minRegex = Pattern.compile("(\\d+)m");
        Pattern secondRegex = Pattern.compile("(\\d+)s");
        Matcher hourMatch = hourRegex.matcher(timeSpan);
        Matcher minMatch = minRegex.matcher(timeSpan);
        Matcher secMatch = secondRegex.matcher(timeSpan);

        boolean hourMatched = hourMatch.find();
        boolean minMatched = minMatch.find();
        boolean secMatched = secMatch.find();

        if (hourMatched || minMatched || secMatched) {
            long hour = 0;
            long min = 0;
            long sec = 0;

            if (hourMatched) {
                hour = Long.parseLong(hourMatch.group(1));
            }

            if (minMatched) {
                min = Long.parseLong(minMatch.group(1));
            }

            if (secMatched) {
                sec = Long.parseLong(secMatch.group(1));
            }

            return (hour * 60 * 60) + (min * 60) + (sec);
        }

        return Long.parseLong(timeSpan) * 60;
    }

    public static long parseLong(String val, long defaultValue) {
        try {
            return Long.parseLong(val);
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    public static Long parseLong(String val) {
        try {
            return Long.parseLong(val);
        } catch (NumberFormatException e) {
            return null;
        }
    }
}

Related

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