如何在Android中获取用户选择的日期格式?

15

我一直在解决Android手机用户选择的日期格式问题。 我已经查看了stackoverflow上的许多问题和答案,但没有得到完美的答案。 例如: 我在手机中选择的日期格式为"Sat, 31 Dec 2011" 但是当我使用stackoverflow上提供的答案时,出现了问题:

DateFormat df = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
tv.setText(df.format(date));

以上代码返回了06/08/2011(月/日/年)格式的日期。 但是请注意我在手机上选择的日期格式。如何获取精确的格式?

3个回答

32
在我目前正在开发的应用程序中,我使用了以下代码,我相信它可以做到你所需要的。
final String format = Settings.System.getString(getContentResolver(), Settings.System.DATE_FORMAT);
if (TextUtils.isEmpty(format)) {
  dateFormat = android.text.format.DateFormat.getMediumDateFormat(getApplicationContext());
} else {
  dateFormat = new SimpleDateFormat(format);
}

这个设置需要使用哪个库? - KJEjava48

4
DateFormat.getDateFormat函数按预期工作,它返回三种可能的格式之一:
  1. MM/DD/YYYY
  2. DD/MM/YYYY
  3. YYYY/MM/DD
我不确定如何设置你的日期格式为"Sat, 31 Dec 2011",但据我所知,原生Android只允许设置上述三种格式之一(设置-》日期和时间-》选择日期格式)。

enter image description here


2

试试这个

Date inDate = inFormat.parse(in);
DateFormat outFormat = android.text.format.DateFormat.getDateFormat(context);
out=outFormat.format(inDate);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接