问题
I have a SimpleDateFormat object that I retrieve from some internationalization utilities. Parsing dates is all fine and good, but I would like to be able show a formatting hint to my users like "MM/dd/yyyy". Is there a way to get the formatting pattern from a SimpleDateFormat object?
回答1:
SimpleDateFormat.toPattern()
Returns a pattern string describing this date format.
回答2:
If you just need to get a pattern string for the given locale, the following worked for me:
/* Obtain the time format per current locale */
public String getTimeFormat(int longfmt) {
Locale loc = Locale.getDefault();
int jlfmt =
(longfmt == 1)?java.text.SimpleDateFormat.LONG:java.text.SimpleDateFormat.SHORT;
SimpleDateFormat sdf =
(SimpleDateFormat)SimpleDateFormat.getTimeInstance(jlfmt, loc);
return sdf.toLocalizedPattern();
}
/* Obtain the date format per current locale */
public String getDateFormat(int longfmt) {
Locale loc = Locale.getDefault();
int jlfmt =
(longfmt == 1)?java.text.SimpleDateFormat.LONG:java.text.SimpleDateFormat.SHORT;
SimpleDateFormat sdf =
(SimpleDateFormat)SimpleDateFormat.getDateInstance(jlfmt, loc);
return sdf.toLocalizedPattern();
}
getDateInstance and getTimeInstance for the given locale are key here.
回答3:
Use toPattern()
or toLocalizedPattern()
method.
回答4:
import java.text.SimpleDateFormat;
public class Sdf {
public static void main( String [] args ) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String patternToUse = sdf.toPattern();
System.out.println( patternToUse );
}
}
来源:https://stackoverflow.com/questions/2761442/getting-pattern-string-from-java-simpledateformat