Java Regex Time Validate parseTime(String str)

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

Description

convert time format into milliseconds

License

Open Source License

Parameter

Parameter Description
str the format string

Return

time in milliseconds

Declaration

public static long parseTime(String str) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 *     Copyright (C) 2018 wysohn// w ww  . jav  a 2  s .co m
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *******************************************************************************/

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

public class Main {
    private static Pattern pattern = Pattern.compile("(\\d+)(h|m|s)");

    /**
     * convert time format into milliseconds
     * @param str the format string
     * @return time in milliseconds
     */
    public static long parseTime(String str) {
        long sum = 0;

        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            switch (matcher.group(2)) {
            case "h":
                sum += Long.parseLong(matcher.group(1)) * 60 * 60 * 1000;
                break;
            case "m":
                sum += Long.parseLong(matcher.group(1)) * 60 * 1000;
                break;
            case "s":
                sum += Long.parseLong(matcher.group(1)) * 1000;
                break;
            }
        }

        return sum;
    }
}

Related

  1. parseTime(String s)
  2. parseTime(String t)
  3. parseTime(String value)
  4. parseTimeDifference(String input)
  5. parseTimeOffset(String s)