Getting pattern string from java SimpleDateFormat

自作多情 提交于 2020-01-01 23:16:52

问题


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?


回答1:


SimpleDateFormat.toPattern()

Returns a pattern string describing this date format.




回答2:


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.




回答3:


Use toPattern() or toLocalizedPattern() method.




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


来源:https://stackoverflow.com/questions/2761442/getting-pattern-string-from-java-simpledateformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!