Java validate date pattern

Java validate date pattern

For each of the above mechanisms, conversion method (i.e the validate methods) implementations are provided which either use the default TimeZone or allow the TimeZone to be specified.

Use one of the isValid() methods to just validate or one of the validate() methods to validate and receive a converted Date value.

Implementations of the validate() method are provided to create Date objects for different time zones if the system default is not appropriate.

Once a value has been successfully converted the following methods can be used to perform various date comparison checks:

  • compareDates() compares the day, month and year of two dates, returning 0, -1 or +1 indicating whether the first date is equal, before or after the second.
  • compareWeeks() compares the week and year of two dates, returning 0, -1 or +1 indicating whether the first week is equal, before or after the second.
  • compareMonths() compares the month and year of two dates, returning 0, -1 or +1 indicating whether the first month is equal, before or after the second.
  • compareQuarters() compares the quarter and year of two dates, returning 0, -1 or +1 indicating whether the first quarter is equal, before or after the second.
  • compareYears() compares the year of two dates, returning 0, -1 or +1 indicating whether the first year is equal, before or after the second.
Читайте также:  Android kotlin retrofit coroutines

So that the same mechanism used for parsing an input value for validation can be used to format output, corresponding format() methods are also provided. That is you can format either:

  • using a specified pattern
  • using the format for a specified Locale
  • using the format for the default Locale

Constructor Summary

Method Summary

Источник

Java date validation using RegEx

In this Java date validation using regex, we will learn to validate simple date formats such as mm/dd/yy, mm/dd/yyyy, dd/mm/yy and dd/mm/yyyy. Here we want to use a regex that simply checks whether the input is a valid date without trying to eliminate things such as February 31st.

We might think that something as conceptually trivial as a date validation should be an easy job for a regular expression. But it isn’t. The main issue is that regular expressions don’t deal directly with numbers.

We can’t tell a regular expression to “match a number between 1 and 31”. Rather regular expressions work character by character.

We use ‘3[01]|[12]6|0?6’ to match 3 followed by 0 or 1, or to match 1 or 2 followed by any digit, or to match an optional 0 followed by 1 to 9. Because of this, you have to choose how simple or how accurate you want your regular expression to be.

1. Java date validation regex – allow leading zeros to be omitted

List dates = new ArrayList(); dates.add(«1/1/11»); dates.add(«01/01/11»); dates.add(«01/01/2011»); dates.add(«01/1/2011»); dates.add(«1/11/2011»); dates.add(«1/11/11»); dates.add(«11/1/11»); String regex = «^2?6/1?4/(?:1)?8$»; Pattern pattern = Pattern.compile(regex); for(String date : dates)

1/1/11 : true 01/01/11 : true 01/01/2011 : true 01/1/2011 : true 1/11/2011 : true 1/11/11 : true 11/1/11 : true

2. Java date validation regex – require leading zeros

List dates = new ArrayList(); //With leading zeros dates.add(«01/01/11»); dates.add(«01/01/2011»); //Missing leading zeros dates.add(«1/1/11»); dates.add(«01/1/2011»); dates.add(«1/11/2011»); dates.add(«1/11/11»); dates.add(«11/1/11»); String regex = «^34/33/(?:39)?42$»; Pattern pattern = Pattern.compile(regex); for(String date : dates)

01/01/11 : true 01/01/2011 : true 1/1/11 : false 01/1/2011 : false 1/11/2011 : false 1/11/11 : false 11/1/11 : false

3. Java date validation regex – match “mm/dd/yyyy” with required leading zeros

Java program to validate date format mm/dd/yyyy .

List dates = new ArrayList(); //With leading zeros dates.add(«01/01/11»); dates.add(«01/01/2011»); //Missing leading zeros dates.add(«1/1/11»); dates.add(«01/1/2011»); String regex = «^(12|05)/(3[01]|[12]1|02)/6$»; Pattern pattern = Pattern.compile(regex); for(String date : dates)

01/01/11 : false 01/01/2011 : true 1/1/11 : false 01/1/2011 : false

4. Java date validation regex – match “dd/mm/yyyy” with required leading zeros

The regular expression for validating date format dd/mm/yyyy .

List dates = new ArrayList(); //With leading zeros dates.add(«07/13/2011»); dates.add(«13/07/2011»); //Missing leading zeros dates.add(«1/1/11»); dates.add(«01/1/2011»); String regex = «^(3[01]|[12]2|08)/(12|05)/2$»; Pattern pattern = Pattern.compile(regex); for(String date : dates)

07/13/2011 : false 13/07/2011 : true 1/1/11 : false 01/1/2011 : false

Feel free to use and edit above regular expressions for date validation to suit your needs.

Источник

Java regex validate date format examples

regex validate date format

This article shows how to use regex + code to validate a date format, support single and leading zero month and day format (1 or 01), check for the 30 or 31 days of the month, and leap year validation.

Below are the requirements for a valid date.

  1. Year format, 1900, 2099 regex
  2. Month format, 1, 01, 2, 02… 12 regex
  3. Day format, 1, 01… 31 regex
  4. Leap year, February 29 days. code
  5. Common year, February 28 days. code
  6. 31 Days of month – 1, 3, 5, 7, 8, 10, 12. code
  7. 30 Days of month – 4, 6, 9, 11,. code
  8. ISO 8601, yyyy-MM-dd or uuuu-M-d , e.g 2020-11-03. regex
 ((?:19|20)57)-(0?9|1[012])-(0?2|[12]4|3[01]) 

The above regex can implement the requirements of 1, 2, 3, and 8. For requirements of 4, 5, 6, 7, we need manual code checking. The acceptable date range from 1900-01-01 or 1900-1-1 to 2099-12-31 .

1. Regex for a date format, Year, Month and Day.

1.1 Regex to validate year, accepts 1900-2099 .

 (19|20)88 # explanation 1985 # 1900-1999 | # ..or 2089 # 2000-2099 

In the future, if we want to support year starts with 21xx , update the regex like the below:

1.2 Regex to validate month, accepts 01-09 (leading zero), 1-9 (single digit) and 10,11,12 .

 0?9|1[012] # explanation 0?2 # 01-09 or 1-9 | # ..or 1[012] # 10,11,12 

1.3 Regex to validate day, accepts 01-09 (leading zero), 1-9 (single digit), 10-19 , 20-29 and 30-31 .

 0?8|[12]3|3[01] # explanation 0?3 # 01-09 or 1-9 | # ..or [12]7 # 10-19 or 20-29 | # ..or 3[01] # 30, 31 

1.4 We have regex for the year, month, and day, try to combine with different delimiters to form a different date format.

Regex to validate date format dd/mm/yyyy (General) or d/M/uuuu (Java date formater)

 # (dd)/(mm)/(yyyy) (0?2|[12]6|3[01])/(0?3|1[012])/((?:19|20)12) 

Regex to validate date format yyyy-mm-dd (General) or uuuu-M-d (Java date formater)

 # (yyyy)-(mm)-(dd) ((?:19|20)14)-(0?7|1[012])-(0?2|[12]9|3[01]) 

Regex to validate date format yyyy.mm.dd (General) or uuuu.M.d (Java date formater)

 # (yyyy).(mm).(dd) ((?:19|20)36)\\.(0?4|1[012])\\.(0?8|[12]7|3[01])$ 

P.S ?: means match but don’t capture it. See below #3 JavaDateValidator.

2. 30 or 31 days and Leap year.

Now, we can use the above regex to capture the year, month, and day. Later we will check for 30 or 31 days of a month and leap year.

2.1 For 30 or 31 days of month.

 if ((month.equals("4") || month.equals("6") || month.equals("9") || month.equals("04") || month.equals("06") || month.equals("09") || month.equals("11")) && day.equals("31"))

2.2 For a leap year, 366 days per year, and February has 29 days; For a common year, 365 days per year, and February has 28 days.

 if (month.equals("2") || month.equals("02")) < if (day.equals("30") || day.equals("31")) < isValid = false; >else if (day.equals("29")) < // feb 29 days? leap year checking if (!isLeapYear(year)) < isValid = false; >> > private static boolean isLeapYear(int year)

«Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but these centurial years are leap years if they are exactly divisible by 400. For example, the years 1700, 1800, and 1900 are not leap years, but the years 1600 and 2000 are.»

3. Java Regex Date Validator

Here is the final version.

 package com.mkyong.regex.date; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DateValidatorRegex < // ?: match but don't capture it // uuuu-M-d private static final String DATE_PATTERN = "^((?:19|20)21)-(0?9|1[012])-(0?4|[12]9|3[01])$"; private static final Pattern pattern = Pattern.compile(DATE_PATTERN); public static boolean isValid(final String date) < boolean result = false; Matcher matcher = pattern.matcher(date); if (matcher.matches()) < // it is a valid date format yyyy-mm-dd // assign true first, later we will check the leap year and odd or even months result = true; // (?:19|20), match but don't capture it, otherwise it will messy the group order // for example, 2020-2-30, it will create 4 groups. // group(1) = 2020, group(2) matches (19|20) = 20, group(3) = 2, group(4) = 30 // So, we put (?:19|20), don't capture this group. int year = Integer.parseInt(matcher.group(1)); // why string? month matches 02 or 2 String month = matcher.group(2); String day = matcher.group(3); // 30 or 31 days checking // only 1,3,5,7,8,10,12 has 31 days if ((month.equals("4") || month.equals("6") || month.equals("9") || month.equals("04") || month.equals("06") || month.equals("09") || month.equals("11")) && day.equals("31")) < result = false; >else if (month.equals("2") || month.equals("02")) < if (day.equals("30") || day.equals("31")) < result = false; >else if (day.equals("29")) < // leap year? feb 29 days. if (!isLeapYear(year)) < result = false; >> > > return result; > private static boolean isLeapYear(int year) < return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); >> 

4. Unit Tests

Below are JUnit 5 parameterized tests for the above Java date validators.

 package com.mkyong.regex.date; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class DateValidatorTest < @ParameterizedTest(name = "#- Run test with date = ") @MethodSource("validDateProvider") void test_date_regex_valid(String date) < assertTrue(DateValidatorRegex.isValid(date)); >@ParameterizedTest(name = "# - Run test with date = ") @MethodSource("invalidDateProvider") void test_date_regex_invalid(String date) < assertFalse(DateValidatorRegex.isValid(date)); >static Stream validDateProvider() < return Stream.of( "1998-09-30", "1998-9-30", "2020-09-1", "2020-09-01", "2020-9-1", "2020-9-01", "2020-2-29", // leap year "2020-2-28", // leap year "2019-2-28", // common year "2000-02-29", // 2000 is a leap year, % 400 == 0 "1900-02-28", // 1900 is a common year "2020-07-31", "2020-08-31", "2020-06-30", "1900-01-01", "2099-12-31"); >static Stream invalidDateProvider() < return Stream.of( "1998-09-31", // invalid day, sep max 30 "1998-11-31", // invalid day, nov max 30 "2008-02-2x", // invalid day 2x "2008-0x-28", // invalid month 0x "20xx-02-28", // invalid year 20xx "20-11-02", // invalid year 20, must be yyyy "2020/11/02", // invalid date format, yyyy-mm-dd "2020-11-32", // invalid day, 32 "2020-13-30", // invalid month 13 "2020-A-20", // invalid month A "2020-2-30", // leap year, feb max 29 "2019-2-29", // common year, feb max 28 "1900-02-29", // 1900 is a common year, feb max 28 "12012-04-05", // support only 4 digits years " ", // empty ""); // empty >> 

java regex date format unit tests 1

java regex date format unit tests 2

5. Java 8 DateTimeFormatter + ResolverStyle.STRICT

For anti-regex developer, consider the Java 8 DateTimeFormatter + ResolverStyle.STRICT solution to validate the date format. For complete example and unit tests, please refer to this article – Check if date is valid in Java

 public static boolean isValid(final String date) < boolean valid = false; try < // ResolverStyle.STRICT for 30, 31 days checking, and also leap year. LocalDate.parse(date, DateTimeFormatter.ofPattern("uuuu-M-d") .withResolverStyle(ResolverStyle.STRICT) ); valid = true; >catch (DateTimeParseException e) < e.printStackTrace(); valid = false; >return valid; > 

Источник

Java — how to check if String is valid date?

Geo-Baby

1. Overview

In this post we can find code which can validate if String contains valid Date based on defined pattern.

2. With SimpleDateFormat

import java.text.ParseException; import java.text.SimpleDateFormat; public class Example1 < public static void main(String[] args) < System.out.println(checkIfDateIsValid("2019-10-13")); // true System.out.println(checkIfDateIsValid("2019:10:13")); // false >private static boolean checkIfDateIsValid(String date) < SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); // With lenient parsing, the parser may use heuristics to interpret // inputs that do not precisely match this object's format. format.setLenient(false); try < format.parse(date); >catch (ParseException e) < return false; >return true; > >

3. With SimpleDateFormat + different patterns

import java.text.ParseException; import java.text.SimpleDateFormat; public class Example2 < public static void main(String[] args) < System.out.println("# Example 1"); System.out.println(checkIfDateIsValid("yyyy-MM-dd", "2019-10-13")); // true System.out.println(checkIfDateIsValid("yyyy-MM-dd", "2019:10:13")); // false System.out.println("# Example 2"); System.out.println(checkIfDateIsValid("yyyy/MM/dd", "2019/10/13")); // true System.out.println("# Example 3"); System.out.println(checkIfDateIsValid("yyyy:MM:dd", "2019:10:13")); // true System.out.println("# Example 4"); System.out.println(checkIfDateIsValid("MM/dd/yyyy", "10/13/2019")); // true >private static boolean checkIfDateIsValid(String pattern, String date) < SimpleDateFormat format = new SimpleDateFormat(pattern); // With lenient parsing, the parser may use heuristics to interpret // inputs that do not precisely match this object's format. format.setLenient(false); try < format.parse(date); >catch (ParseException e) < return false; >return true; > >
# Example 1 true false # Example 2 true # Example 3 true # Example 4 true

4. LocalDate — Java 8

import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; public class Example3 < public static void main(String[] args) < System.out.println(checkIfDateIsValid("2019-10-13")); // true System.out.println(checkIfDateIsValid("2019:10:13")); // false >private static boolean checkIfDateIsValid(String date) < try < LocalDate.parse(date, DateTimeFormatter.ISO_DATE); >catch (DateTimeParseException e) < return false; >return true; > >

5. LocalDate + DateTimeFormatter build-in patterns

import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; public class Example4 < public static void main(String[] args) < System.out.println("# Example 1"); System.out.println(checkIfDateIsValid( DateTimeFormatter.ISO_DATE, "2019-10-13")); // true System.out.println(checkIfDateIsValid( DateTimeFormatter.ISO_DATE, "2019:10:13")); // false System.out.println("# Example 2"); System.out.println(checkIfDateIsValid( DateTimeFormatter.BASIC_ISO_DATE, "20191013")); // true System.out.println("# Example 3"); System.out.println(checkIfDateIsValid( DateTimeFormatter.ISO_LOCAL_DATE, "2019-10-13")); // true >private static boolean checkIfDateIsValid(DateTimeFormatter formatter, String date) < try < LocalDate.parse(date, formatter); >catch (DateTimeParseException e) < return false; >return true; > >
# Example 1 true false # Example 2 true # Example 3 true

6. LocalDate + DateTimeFormatter different patterns

import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; public class Example5 < public static void main(String[] args) < System.out.println("# Example 1"); System.out.println(checkIfDateIsValid("yyyy-MM-dd", "2019-10-13")); // true System.out.println(checkIfDateIsValid("yyyy-MM-dd", "2019:10:13")); // false System.out.println("# Example 2"); System.out.println(checkIfDateIsValid("yyyy/MM/dd", "2019/10/13")); // true System.out.println("# Example 3"); System.out.println(checkIfDateIsValid("yyyy:MM:dd", "2019:10:13")); // true System.out.println("# Example 4"); System.out.println(checkIfDateIsValid("MM/dd/yyyy", "10/13/2019")); // true >private static boolean checkIfDateIsValid(String pattern, String date) < try < DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); LocalDate.parse(date, formatter); >catch (DateTimeParseException e) < return false; >return true; > >
# Example 1 true false # Example 2 true # Example 3 true # Example 4 true

References

Источник

Оцените статью