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 i开发者_如何学PythonnDateFormat
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 method Date.parse(String)
. It may or may not actually support those syntaxes.
From javadoc of Date.parse(String)
:
It accepts many syntaxes; in particular, it recognizes the IETF standard date syntax: "Sat, 12 Aug 1995 13:30:00 GMT". It also understands the continental U.S. time-zone abbreviations, but for general use, a time-zone offset should be used: "Sat, 12 Aug 1995 13:30:00 GMT+0430" (4 hours, 30 minutes west of the Greenwich meridian). If no time zone is specified, the local time zone is assumed. GMT and UTC are considered equivalent.
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 SimpleDateFormat
is the way to go for parsing Dates. See A non-deprecated exact equivalent of Date(String s) in Java?
I was interested by your question so checked the JavaDoc for SimpleDateFormat, DateFormat, Date, and Calendar to see if I could work this out.
If you know the date string being passed in will always be in the format suitable for the current Locale you could use the factory methods in DateFormat, the GetDateInstance methods.
Other than that... I'd have to say no. At least not to my knowledge.
I'll watch this question with interest.
精彩评论