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?
4 Answers
Returns a pattern string describing this date format.
-
-
Can you tell me, how to get just the date or time pattern from this string? I can use String methods like compare and contains, but is there a more elegant method than doing this?– ParagJNov 4, 2014 at 9:38
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.
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 );
}
}