从java SimpleDateFormat获取模式字符串

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

SimpleDateFormat.toPattern()

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

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

 /* 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和getTimeInstance是关键。

使用toPattern()toLocalizedPattern()方法。

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