Java: Check the Date Format of Current String Is According to Required Format or Not

In Java how to check if a string(holding datetime value) is according to datetime format YYYYMMDDTHHMMSSZ

java.time

I recommend java.time, the modern Java date and time API, for your date and time work. I suggest:

private static final DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmssX")
.withResolverStyle(ResolverStyle.STRICT);

public static boolean isParseableBasicIso8601(String str) {
try {
OffsetDateTime odt = OffsetDateTime.parse(str, formatter);
return odt.getOffset().equals(ZoneOffset.UTC);
} catch (DateTimeParseException dtpe) {
return false;
}
}

To try it out:

    String[] testStrings = {
"20210223T234556Z",
"Cannot be parsed",
"20210229T234556Z",
"20210223T234556+08",
"20210223T234556+00",
};

for (String s : testStrings) {
System.out.format("%-18s? %s%n", s, isParseableBasicIso8601(s));
}

Output is:

20210223T234556Z  ? true
Cannot be parsed ? false
20210229T234556Z ? false
20210223T234556+08? false
20210223T234556+00? true

The third example shows that Java knows that 2021 is not a leap year. ResolverStyle.STRICT causes it to reject February 29. In the fourth example the UTC offset is wrong. Accepting the last example is not what you asked for. In ISO 8601 format (which your format is), an offset of zero from UTC is usually denoted Z, but +00 is accepted too. If you want to reject this, the solution is in the comment by Mad Programmer: format the date-time back using the same formatter and only accept if the two strings are equal.

Consider adding a range check and reject dates and times that are unreasonably far in the past or the future. Use OffsetDateTime.isBefore() or isAfter() for comparison.

Links

  • Oracle tutorial: Date Time explaining how to use java.time.
  • Wikipedia article: ISO 8601

how to check if a date pattern is valid in java?

tl;dr

Try DateTimeFormatter.ofPattern while trapping for IllegalArgumentException.

try {
formatter = DateTimeFormatter.ofPattern( input ) ;
} catch ( IllegalArgumentException e ) {
… // Handle exception thrown for invalid input formatting pattern.
}

Better yet, let DateTimeFormatter.ofLocalized… automatically localize instead of you trying to allow troublesome arbitrary format strings.

Localize, instead

Accepting any arbitrary formatting pattern is going to be a problematic headache. Formatting patterns are complicated and subtle.

In addition, many of the formats will require that you also specify a Locale to determine the human language and cultural norms necessary to decide issues such as translation of month name & day-of-week name & so on, abbreviation, capitalization, punctuation, and more.

I suggest you instead let java.time localize. Instead of passing a formatting pattern, you would pass a FormatStyle enum object (or string of its name), and a Locale object. But as I mentioned above, you need to pass a Locale in any event.

Use the FormatStyle and Locale to get a localizing DateTimeFormatter object.

FormatStyle style = FormatStyle.MEDIUM ;
Locale locale = Locale.CANADA_FRENCH ;

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( style ).withLocale( locale ) ;
LocalDate localDate = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
String output = localDate.format( formatter ) ;

See this code run live at IdeOne.com.

12 juill. 2021

Trap IllegalArgumentException

If you insist on your approach of accepting arbitrary formatting patterns, you can attempt to use that format with DateTimeFormatter class. Call its ofPattern method. Trap for the IllegalArgumentException thrown if the pattern is invalid.

String input = "dd/mm/yyyy" ;
DateTimeFormatter f = null ;
try {
formatter = DateTimeFormatter.ofPattern( input ) ;
} catch ( IllegalArgumentException e ) {
… // Handle exception thrown for invalid input formatting pattern.
}

Beware: As mentioned above, some formats require a Locale. So you should be receiving a locale argument as well as a formatting pattern, and calling DateTimeFormatter.withLocale.

What is best ways to validate string date to be valid date according to format?

If you are using java 8 then DateTimeFormatter is what you are looking for. The link to javadoc also contains sample code and a number of predefined formats. Besides you can also define your own.


Here is some code, an example from the same link:

LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);

Also, this How to parse/format dates with LocalDateTime? (Java 8) question has got some fantastic answers.


EDIT: Thanks Basil Bourque for the updates about ThreeTen-Backport project in case one needs to use almost the same features as provided by java 8 in some older versions of java.

How can I show the numbers of valid dates in Java?

You can parse each date and its numbers in a try/catch block, and increment a counter as follows:

public static void main(String[] args) {
String[] dates = new String[]{"car","bench","01/04/2019", "01/13/2019", "29/02/200s"};
System.out.println(validate(dates));
}
private static int validate(String[] dates){
int count = 0;
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
format.setLenient(false);
for(String date : dates) {
try {
format.parse(date);
String[] dateParts = date.split("/");
for(String str : dateParts)
Integer.parseInt(str);
if(dateParts.length!=3 || dateParts[0].length()!=2 || dateParts[1].length()!=2 || dateParts[2].length()!=4)
throw new Exception();
count++;
} catch (Exception e) {
System.out.println("Date " + date + " is not valid");
}
}
return count;
}

Output:

Date car is not valid
Date bench is not valid
Date 01/13/2019 is not valid
Date 29/02/200s is not valid
1

EDIT :
According to Ole's comment and this post, it's better to use more accurate libraries:

public static void main(String[] args) {
String[] dates = new String[]{"car","bench","01/04/2019", "01/13/2019", "29/02/200s"};
System.out.println(validate(dates));
}
private static int validate(String[] dates){
int count = 0;
for(String date : dates) {
try {
String[] dateParts = date.split("/");
if(dateParts.length==3 && isDateValid(Integer.parseInt(dateParts[2]), Integer.parseInt(dateParts[1]), Integer.parseInt(dateParts[0])))
count++;
else
throw new Exception();
} catch (Exception e) {
System.out.println("Date " + date + " is not valid");
}
}
return count;
}
private static boolean isDateValid(int year, int month, int day) {
boolean dateIsValid = true;
try {
LocalDate.of(year, month, day);
} catch (DateTimeException e) {
dateIsValid = false;
}
return dateIsValid;
}

How to check if given string is of specific date format?

Use the class

http://www.gwtproject.org/javadoc/latest/com/google/gwt/i18n/shared/DateTimeFormat.html#parse(java.lang.String)

Which is in shared package.

Not the clinet package class

http://www.gwtproject.org/javadoc/latest/com/google/gwt/i18n/client/DateTimeFormat.html#parse(java.lang.String)

How to check if a string is date?

Other person are also correct

This is your answer

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class date {
public static boolean isValidDate(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:ms");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}

public static void main(String[] args) {

System.out.println(isValidDate("20-01-2014"));
System.out.println(isValidDate("11-04-2015 22:01:33:023"));

System.out.println(isValidDate("32476347656435"));
}
}

Check the date format of string if it's according to required format or not

Just same like Java, check if it can parse properly

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd hh:mm:ss"
let someDate = "string date"

if dateFormatterGet.date(from: someDate) != nil {
// valid format
} else {
// invalid format
}


Related Topics



Leave a reply



Submit