Java Regex Time Validate parseTimeOffset(String s)

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

Description

Parses time offset from string (Examples: "-1d", "+1mon")

License

Open Source License

Parameter

Parameter Description
s string to parse

Return

number of seconds in the offset

Declaration

public static Long parseTimeOffset(String s) 

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 {
    private static Pattern timeOffsetPattern = Pattern.compile("^([+-]?)(\\d+)([a-z]+)$");

    /**// w w  w .  jav a  2s.c o  m
     * Parses time offset from string (Examples: "-1d", "+1mon")
     *
     * @param s string to parse
     * @return number of seconds in the offset
     */
    public static Long parseTimeOffset(String s) {
        Matcher matcher = timeOffsetPattern.matcher(s.replaceAll("^['\"]|['\"]$", ""));

        if (!matcher.matches())
            return 0L;

        int sign = matcher.group(1).equals("+") ? 1 : -1;
        long offset = Integer.parseInt(matcher.group(2)) * getUnitValue(matcher.group(3));

        return offset * sign;
    }

    private static long getUnitValue(String s) {
        if (s.startsWith("s")) {
            return 1;
        } else if (s.startsWith("min")) {
            return 60;
        } else if (s.startsWith("h")) {
            return 3600;
        } else if (s.startsWith("d")) {
            return 86400;
        } else if (s.startsWith("w")) {
            return 604800;
        } else if (s.startsWith("mon")) {
            return 18144000;
        } else if (s.startsWith("y")) {
            return 31536000;
        } else {
            return 60;
        }
    }
}

Related

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