Ich wollte wissen, dass es eine beliebige Methode in Java gibt, die dies tun kann. Andernfalls kann ich mich für eine Regex-Lösung entscheiden.
Ich habe eine Zeichenfolge vom Benutzer, die beliebige Zeichen sein kann. Und ich möchte überprüfen, ob die Eingabezeichenfolge meinem gewünschten Datumsformat entspricht oder nicht .
Da ich 20130925 eingegeben habe und mein erforderliches Format istdd/MM/jjjj , sollte ich für diesen Fall false ..__ bekommen.
Ich möchte dieses Datum nicht konvertieren. Ich möchte nur prüfen, ob die Eingabezeichenfolge dem erforderlichen Datumsformat entspricht oder nicht.
Ich habe folgendes versucht
Date date = null;
try {
date = new SimpleDateFormat("dd/MM/yyyy").parse("20130925");
} catch (Exception ex) {
// do something for invalid dateformat
}
mein catch (Exception ex) -Block kann jedoch keine von SimpleDateFormat.Parse () generierten Ausnahmen abfangen.
Es ist von Natur aus unmöglich, einen String in einem unbekannten Format auf den Datums-/Zeitwert zurück zu analysieren (lassen Sie uns ehrlich sein, was bedeutet 3/3/3
eigentlich ?!). Alles, was wir tun können, ist "Best Effort".
Diese Lösung nicht wirft eine Exception
, gibt eine boolean
zurück, dies ist von Entwurf. Alle Exception
s werden nur als Schutzmechanismus verwendet.
Da es jetzt 2018 ist und Java 8+ die Datums-/Zeit-API hat (und der Rest den ThreeTen-Backport hat). Die Lösung bleibt im Wesentlichen die gleiche, wird jedoch etwas komplizierter, da wir Folgendes prüfen müssen:
So sieht es aus wie ...
public static boolean isValidFormat(String format, String value, Locale locale) {
LocalDateTime ldt = null;
DateTimeFormatter fomatter = DateTimeFormatter.ofPattern(format, locale);
try {
ldt = LocalDateTime.parse(value, fomatter);
String result = ldt.format(fomatter);
return result.equals(value);
} catch (DateTimeParseException e) {
try {
LocalDate ld = LocalDate.parse(value, fomatter);
String result = ld.format(fomatter);
return result.equals(value);
} catch (DateTimeParseException exp) {
try {
LocalTime lt = LocalTime.parse(value, fomatter);
String result = lt.format(fomatter);
return result.equals(value);
} catch (DateTimeParseException e2) {
// Debugging purposes
//e2.printStackTrace();
}
}
}
return false;
}
Das macht folgendes ...
System.out.println("isValid - dd/MM/yyyy with 20130925 = " + isValidFormat("dd/MM/yyyy", "20130925", Locale.ENGLISH));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 = " + isValidFormat("dd/MM/yyyy", "25/09/2013", Locale.ENGLISH));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = " + isValidFormat("dd/MM/yyyy", "25/09/2013 12:13:50", Locale.ENGLISH));
System.out.println("isValid - yyyy-MM-dd with 2017-18--15 = " + isValidFormat("yyyy-MM-dd", "2017-18--15", Locale.ENGLISH));
ausgabe...
isValid - dd/MM/yyyy with 20130925 = false
isValid - dd/MM/yyyy with 25/09/2013 = true
isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = false
isValid - yyyy-MM-dd with 2017-18--15 = false
Versuchen Sie einfach, die String
zur gewünschten Date
zu analysieren, indem Sie etwas wie SimpleDateFormat
verwenden.
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
date = null;
}
} catch (ParseException ex) {
ex.printStackTrace();
}
if (date == null) {
// Invalid date format
} else {
// Valid date format
}
Sie könnten dann einfach eine einfache Methode schreiben, die diese Aktion ausführte und true
zurückgab, wenn Date
nicht null war.
Als Vorschlag ...
Mit laufendem Beispiel aktualisiert
Ich bin nicht sicher, was Sie tun, aber das folgende Beispiel ...
import Java.text.ParseException;
import Java.text.SimpleDateFormat;
import Java.util.Date;
public class TestDateParser {
public static void main(String[] args) {
System.out.println("isValid - dd/MM/yyyy with 20130925 = " + isValidFormat("dd/MM/yyyy", "20130925"));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 = " + isValidFormat("dd/MM/yyyy", "25/09/2013"));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = " + isValidFormat("dd/MM/yyyy", "25/09/2013 12:13:50"));
}
public static boolean isValidFormat(String format, String value) {
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
date = null;
}
} catch (ParseException ex) {
ex.printStackTrace();
}
return date != null;
}
}
Ausgänge (sowas) ...
Java.text.ParseException: Unparseable date: "20130925"
isValid - dd/MM/yyyy with 20130925 = false
isValid - dd/MM/yyyy with 25/09/2013 = true
isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = false
at Java.text.DateFormat.parse(DateFormat.Java:366)
at javaapplication373.JavaApplication373.isValidFormat(JavaApplication373.Java:28)
at javaapplication373.JavaApplication373.main(JavaApplication373.Java:19)
Nicht richtig. Für isValidFormat ("JJJJ-MM-TT", "2017-18-15"); keine Ausnahme auslösen.
isValid - yyyy-MM-dd", "2017-18--15 = false
Scheint wie erwartet für mich zu funktionieren - die Methode ist nicht auf die Ausnahme allein angewiesen (oder wirft sie auch nicht), um ihre Operation auszuführen
Für Ihren Fall können Sie Regex verwenden:
boolean checkFormat;
if (input.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})"))
checkFormat=true;
else
checkFormat=false;
Für einen größeren Umfang oder wenn Sie eine flexible Lösung wünschen, lesen Sie MadProgrammer's answer.
Fast 5 Jahre nach dem Posten dieser Antwort stelle ich fest, dass dies eine dumme Methode ist, ein Datumsformat zu validieren. Aber ich lasse das hier, um den Leuten mitzuteilen, dass die Verwendung von Regex zur Validierung eines Datums inakzeptabel ist
Sie können dies zur einfachen Überprüfung des Datumsformats versuchen
public Date validateDateFormat(String dateToValdate) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HHmmss");
//To make strict date format validation
formatter.setLenient(false);
Date parsedDate = null;
try {
parsedDate = formatter.parse(dateToValdate);
System.out.println("++validated DATE TIME ++"+formatter.format(parsedDate));
} catch (ParseException e) {
//Handle exception
}
return parsedDate;
}
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
formatter.setLenient(false);
try {
Date date= formatter.parse("02/03/2010");
} catch (ParseException e) {
//If input date is in different format or invalid.
}
formatter.setLenient (false) erzwingt eine strikte Übereinstimmung.
Wenn Sie Joda-Time verwenden -
private boolean isValidDate(String dateOfBirth) {
boolean valid = true;
try {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime dob = formatter.parseDateTime(dateOfBirth);
} catch (Exception e) {
valid = false;
}
return valid;
}
Wenn Sie beispielsweise möchten, dass das Datumsformat "03.11.2017" ist
if (String.valueOf(DateEdit.getText()).matches("([1-9]{1}|[0]{1}[1-9]{1}|[1]{1}[0-9]{1}|[2]{1}[0-9]{1}|[3]{1}[0-1]{1})" +
"([.]{1})" +
"([0]{1}[1-9]{1}|[1]{1}[0-2]{1}|[1-9]{1})" +
"([.]{1})" +
"([20]{2}[0-9]{2})"))
checkFormat=true;
else
checkFormat=false;
if (!checkFormat) {
Toast.makeText(getApplicationContext(), "incorrect date format! Ex.23.06.2016", Toast.LENGTH_SHORT).show();
}
Hier ist eine einfache Methode:
public static boolean checkDatePattern(String padrao, String data) {
try {
SimpleDateFormat format = new SimpleDateFormat(padrao, LocaleUtils.DEFAULT_LOCALE);
format.parse(data);
return true;
} catch (ParseException e) {
return false;
}
}
Eine Kombination aus Regex und SimpleDateFormat ist die richtige Antwort, die ich glaube. SimpleDateFormat fängt keine Ausnahme ab, wenn die einzelnen Komponenten ungültig sind, dh, Format definiert: JJJJ-MM-TT Eingabe: 201-0-12Es wird keine Ausnahme ausgelöst. Dieser Fall sollte behandelt werden. Aber mit dem Regex, wie er von Sok Pomaranczowy und Baby vorgeschlagen wird, wird er sich um diesen speziellen Fall kümmern.