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?
SimpleDateFormat format() Method in Java with Examples Return Value: The method returns Date or time in string format of mm/dd/yyyy.
Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.
The java SimpleDateFormat allows construction of arbitrary non-localized formats. The java DateFormat allows construction of three localized formats each for dates and times, via its factory methods.
SimpleDateFormat.toPattern()
Returns a pattern string describing this date format.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With