Android SimpleDateFormat警告

一、警告代码:

 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");

二、警告内容:

原文:To get local formatting use getDateInstance(), getDateTimeInstance(), or getTimeInstance(), or use new SimpleDateFormat(String template, Locale locale) with for example Locale.US for ASCII dates.

翻译:若要获取本地格式,请使用getDateInstance()、getDateTimeInstance()或getTimeInstance(),或者使用新的SimpleDataFormat(String template, Locale locale),例如将Locale.US用于ASCII日期。

三、原因分析:

使用 SimpleDateFormat(String pattern) 构造函数,这意味着使用默认语言环境,正如Android语言环境文档所说,要警惕使用默认语言环境,这可能会导致出现错误。

四、解决方案:

方法一:

使用 SimpleDateFormat(String pattern, Locale locale) 构造函数,它将接受一个附加参数 - 你要使用的语言环境。如果你想以一致的方式确保输出是机器可读的(始终看起来相同,无论用户的实际语言环境如何),你可以选择 Locale.US。如果你不关心机器的可红性,你可以使用 Locale.getDefault()

// for US
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss", Locale.US);

// or for default
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());

方法二:

使用 DateFormat 类中的 getDateInstance()getDateTimeInstance()getTimeInstance() 方法:链接

五、API

1、SimpleDateFormat链接

2、DateFormat链接

猜你喜欢

转载自blog.csdn.net/notthin/article/details/121536163