Is there a way whereby the date format can be determined in Java similar to .Net?
Consider the following example:
private String reformatDateString(String dateParam){
if(dateParam == null || dateParam.isEmpty()){
return null;
}
try{
SimpleDateFormat inDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date fromDate = inDateFormat.parse(dateParam);
SimpleDateFormat outDateForm = new SimpleDateFormat("yy-MM-dd");
return outDateForm.format(fromDate);
} catch(ParseException e){
e.printStackTrace();
return null;
}
}
Is there an easier way for the parser to know the inDateFormat instead of strictly providing the two formats?
The best way that I can think of is the old
Date(String)constructor which relies on static methodDate.parse(String). It may or may not actually support those syntaxes.From javadoc of
Date.parse(String):Unfortunately this method is deprecated in favor of explicitly requiring the date format so you will need to use a helper method. Your code above is already a good start, so I recommend just expanding what you have. The documentation of the .NET date parsing function probably lists the formats supported. With your own implementation there will be a clear precedence of formats and no ambiguity.
A quick search revealed other questions indicating that
SimpleDateFormatis the way to go for parsing Dates. See A non-deprecated exact equivalent of Date(String s) in Java?