Java Regex Time Validate parseTimestamp(String s)

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

Description

parse Timestamp

License

Open Source License

Declaration

public static long parseTimestamp(String s) 

Method Source Code

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

import java.util.concurrent.TimeUnit;

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

public class Main {
    public static final Pattern TIMESTAMP_PATTERN = Pattern.compile(
            "(-?\\d+)\\s*((?:d(?:ay(?:s)?)?)|(?:h(?:our(?:s)?)?)|(?:m(?:in(?:ute(?:s)?)?)?)|(?:s(?:ec(?:ond(?:s)?)?)?))?");

    public static long parseTimestamp(String s) {
        s = s.toLowerCase();/*from   w w  w .  j  a v  a 2s  .  c om*/
        long ms = 0;

        Matcher matcher = TIMESTAMP_PATTERN.matcher(s);

        while (matcher.find()) {
            String numStr = matcher.group(1);
            String unitStr = matcher.group(2);

            TimeUnit unit;
            if (unitStr == null) {
                unit = TimeUnit.SECONDS;
            } else
                switch (unitStr) {
                case "d":
                case "day":
                case "days":
                    unit = TimeUnit.DAYS;
                    break;
                case "h":
                case "hour":
                case "hours":
                    unit = TimeUnit.HOURS;
                    break;
                case "m":
                case "min":
                case "minute":
                case "minutes":
                    unit = TimeUnit.MINUTES;
                    break;
                case "s":
                case "sec":
                case "second":
                case "seconds":
                default:
                    unit = TimeUnit.SECONDS;
                    break;
                }
            ms += unit.toMillis(Long.parseLong(numStr));
        }
        return ms;
    }
}

Related

  1. parseTimeOffset(String s)
  2. parseTimePeriod(String period)
  3. parseTimePeriod(String s)
  4. parseTimeSpan(String timeSpan)
  5. parseTimestamp(final String value)
  6. parseTimeString(String str)
  7. parseTimeString(String str, TimeUnit unit)
  8. parseTimeString(String time)