27

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 4

36

SimpleDateFormat.toPattern()

Returns a pattern string describing this date format.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I guess I didn't look close enough.
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?
6

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.

Comments

5

Use toPattern() or toLocalizedPattern() method.

Comments

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 );
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.