从java SimpleDateFormat获取模式字符串

DLa*_*Law 26 java simpledateformat

我有一个SimpleDateFormat对象,我从一些国际化实用程序检索.解析日期都很好,但我希望能够向我的用户显示格式提示,如"MM/dd/yyyy".有没有办法从SimpleDateFormat对象获取格式模式?

ska*_*man 32

SimpleDateFormat.toPattern()

返回描述此日期格式的模式字符串.


小智 6

如果您只需要获取给定语言环境的模式字符串,则以下内容适用于我:

/* 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();
}
Run Code Online (Sandbox Code Playgroud)

给定语言环境的getDateInstance和getTimeInstance是关键.


小智 5

使用toPattern()toLocalizedPattern()方法。