从 java SimpleDateFormat 获取模式字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2761442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting pattern string from java SimpleDateFormat
提问by DLaw
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?
我有一个 SimpleDateFormat 对象,我从一些国际化实用程序中检索到它。解析日期很好,但我希望能够向我的用户显示格式提示,例如“MM/dd/yyyy”。有没有办法从 SimpleDateFormat 对象中获取格式化模式?
回答by doublep
Use toPattern()
or toLocalizedPattern()
method.
用途toPattern()
或toLocalizedPattern()
方法。
回答by skaffman
Returns a pattern string describing this date format.
返回描述此日期格式的模式字符串。
回答by OscarRyz
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 );
}
}
回答by Dmitry
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.
给定语言环境的 getDateInstance 和 getTimeInstance 是这里的关键。