12-Hour Time (H:MM AM/PM) Regex for Java
/^(1[0-2]|0?[1-9]):([0-5][0-9])(?::([0-5][0-9]))?\s?(AM|PM|am|pm|Am|Pm)$/iWhat this pattern does
This page provides a well-structured, multi-part regular expression for matching 12-hour time (h:mm am/pm), ported and verified for Java. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.
Java Implementation
// 12-Hour Time (H:MM AM/PM)
// ReDoS-safe | RegexVault — Localization > Time Formats
import java.util.regex.Pattern;
public class 12hourTimeHmmAmpmValidator {
private static final Pattern PATTERN =
Pattern.compile("^(1[0-2]|0?[1-9]):([0-5][0-9])(?::([0-5][0-9]))?\\s?(AM|PM|am|pm|Am|Pm)$");
public static boolean validate(String input) {
return PATTERN.matcher(input).matches();
}
// Example
public static void main(String[] args) {
System.out.println(validate("12:30 PM")); // true
}
}Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
12:30 PM | 13:00 PM |
1:05 AM | 0:30 AM |
11:59:59 PM | 12:60 PM |
12:00 AM | 12:30 |
9:30am | 12:30 pm extra |
12:00PM | — |
When to use this pattern
This pattern is drawn from the Localization > Time Formats category and carries a ReDoS-safe certification. That matters for Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
12:00 AM (midnight) and 12:00 PM (noon) confuse even native English speakers. Consider rejecting 12-hour format for any time-critical input and requiring 24-hour instead.
Technical Notes
12:00 AM = midnight, 12:00 PM = noon — the most commonly confused values. 12-hour format is standard in US, UK, Australia, and parts of Asia. Many others use 24-hour exclusively.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern