开发者

Getting pattern string from java SimpleDateFormat

I have a SimpleDateFormat object that I retrieve开发者_Python百科 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.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.


Use toPattern() or toLocalizedPattern() method.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜