Skip to content

Instantly share code, notes, and snippets.

@agilepoodle
Last active December 13, 2015 17:29
Show Gist options
  • Save agilepoodle/4948474 to your computer and use it in GitHub Desktop.
Save agilepoodle/4948474 to your computer and use it in GitHub Desktop.
package org.jussimononen;
import static java.lang.Integer.valueOf;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.joda.time.IllegalFieldValueException;
import org.joda.time.LocalTime;
public class TimeValidator {
private static final int HOUR_GROUP_INDEX = 1;
private static final int MINUTE_GROUP_INDEX = 2;
private static final Pattern VALID_TIME_RE = Pattern.compile("^\\d{1,2}[:,.]\\d{2}$");
private static final Pattern SPLIT_TIME_RE = Pattern.compile("(\\d{1,2})[:,.](\\d{2})");
public boolean isValid(String timeString) {
if (isValidFormat(timeString.replaceAll("\\s", ""))) {
Time time = extractTimeComponents(timeString);
if (isValidHour(time.hours) && isValidMinutes(time.minutes)) {
return true;
}
}
return false;
}
public Boolean isValid2(String timeString) {
if (isValidFormat(timeString.replaceAll("\\s", ""))) {
Time time = extractTimeComponents(timeString);
try {
LocalTime localTime = new LocalTime(valueOf(time.hours), valueOf(time.minutes));
} catch (IllegalFieldValueException ex) {
return false;
}
return true;
}
return false;
}
private Time extractTimeComponents(String timeString) {
Matcher matcher = SPLIT_TIME_RE.matcher(timeString);
matcher.find();
return new Time(matcher.group(HOUR_GROUP_INDEX), matcher.group(MINUTE_GROUP_INDEX));
}
private boolean isValidFormat(String time) {
return VALID_TIME_RE.matcher(time).find();
}
private boolean isValidMinutes(String minutes) {
return valueOf(minutes) < 59 && valueOf(minutes) >= 0;
}
private boolean isValidHour(String hours) {
return valueOf(hours) < 24 && valueOf(hours) >= 0;
}
private class Time {
public final String hours;
public final String minutes;
public Time(String hours, String minutes) {
this.hours = hours;
this.minutes = minutes;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment