Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting pattern string from java SimpleDateFormat

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?

like image 948
DLaw Avatar asked May 03 '10 21:05

DLaw


People also ask

What does SimpleDateFormat return?

SimpleDateFormat format() Method in Java with Examples Return Value: The method returns Date or time in string format of mm/dd/yyyy.

Is SimpleDateFormat deprecated?

Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.

What is the use of SimpleDateFormat in java?

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.

What is the difference between DateFormat and SimpleDateFormat?

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.


2 Answers

SimpleDateFormat.toPattern()

Returns a pattern string describing this date format.

like image 161
skaffman Avatar answered Sep 22 '22 04:09

skaffman


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.

like image 33
Dmitry Avatar answered Sep 22 '22 04:09

Dmitry