在SQL Server中合并验证DD-MMM-YYYY与DD MMM YYYY日期格式的方法
Absolutely you can merge those two validation routines into one—no need to maintain separate code for each date format! Let’s break down how to do this cleanly, depending on whether you just need to check the format structure or also validate that the date is actually a real, existing date.
JavaScript Solutions
Option 1: Regex Validation (Format-Only Check)
If you just want to verify the input matches either format (without checking if the date is logically valid, like rejecting 31 February), you can use a regex that accepts either a space or hyphen as the separator.
function validateDate(dateStr) { // Matches DD MMM YYYY or DD-MMM-YYYY, case-insensitive const datePattern = /^(0[1-9]|[12][0-9]|3[01]) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4}$|^(0[1-9]|[12][0-9]|3[01])-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}$/i; return datePattern.test(dateStr); } // Test it out! console.log(validateDate("25 Dec 2023")); // ✅ true console.log(validateDate("25-Dec-2023")); // ✅ true console.log(validateDate("32 Jan 2023")); // ❌ false (invalid day) console.log(validateDate("25 Xyz 2023")); // ❌ false (invalid month)
Option 2: Date Parsing (Full Date Validity Check)
For a more robust check that ensures the date actually exists (e.g., rejecting 29 Feb 2021 since it’s not a leap year), normalize the input first then use the Date object to validate.
function validateDate(dateStr) { // Normalize hyphens to spaces so we can parse consistently const normalizedDate = dateStr.replace(/-/g, ' '); const parsedDate = new Date(normalizedDate); // Check if the date is valid and matches the original input components const [day, month, year] = normalizedDate.split(' '); const isDateValid = !isNaN(parsedDate.getTime()) && parsedDate.getDate() === parseInt(day) && parsedDate.toLocaleString('en-US', { month: 'short' }).toLowerCase() === month.toLowerCase() && parsedDate.getFullYear() === parseInt(year); // Ensure the original input uses consistent separators (no mixing spaces and hyphens) const formatIsValid = /^(0[1-9]|[12][0-9]|3[01])( |-)(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\2\d{4}$/i.test(dateStr); return isDateValid && formatIsValid; } // Test cases console.log(validateDate("29 Feb 2020")); // ✅ true (leap year) console.log(validateDate("29 Feb 2021")); // ❌ false (not a leap year) console.log(validateDate("25-Dec-2023")); // ✅ true console.log(validateDate("25 Dec 2023")); // ✅ true console.log(validateDate("2023 Dec 25")); // ❌ false (wrong order)
Java Solution
For Java, you can use DateTimeFormatter with optional separator syntax to handle both formats, plus strict resolution to reject invalid dates.
import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Locale; public class DateValidator { public static boolean validateDate(String dateStr) { // Formatter accepts either space or hyphen as separator, strict mode rejects invalid dates DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd[ ][-]MMM[-][ ]uuuu", Locale.ENGLISH) .withResolverStyle(java.time.format.ResolverStyle.STRICT); try { LocalDate.parse(dateStr, formatter); // Ensure separators are consistent (no mixing spaces and hyphens) boolean hasSpace = dateStr.contains(" "); boolean hasHyphen = dateStr.contains("-"); return !(hasSpace && hasHyphen); } catch (DateTimeParseException e) { return false; } } public static void main(String[] args) { System.out.println(validateDate("25 Dec 2023")); // ✅ true System.out.println(validateDate("25-Dec-2023")); // ✅ true System.out.println(validateDate("31 Feb 2023")); // ❌ false System.out.println(validateDate("25-Dec 2023")); // ❌ false (mixed separators) } }
Quick Note
- Use regex if you only need to validate the format structure (fast, simple).
- Use date parsing if you need to ensure the date is logically valid (handles leap years, month day limits, etc.).
内容的提问来源于stack exchange,提问作者Dinesh

