根据语言使用不同的时间格式 [英] Use different time formats according to language
问题描述
我应该根据我的应用程序中的语言显示不同的时间格式.当设备为英语时,用户应获得以下时间格式:
I'm supposed to show different time formats according to the language in my app. When the device is English the user should get the time format like this:
2018年3月18日,下午2.30
18 March 2018, 2.30 pm
但是当用户的设备是德语时,他应该获得如下时间格式:
But when the user's device is German he should get the time format like this:
18.03.2018,14:30 Uhr
18.03.2018, 14:30 Uhr
是否可以通过使用 SimpleDateFormat
格式化时间 String
来做到这一点,或者我应该以另一种方式来做到这一点?这样吗?
Is there any way to do this by formatting the time String
with SimpleDateFormat
or am I supposed to do this in another way and if so, how am I able to do this?
推荐答案
我认为它不起作用,但确实可以.只需将您喜欢的格式放在字符串xml文件中,对我来说就是这样:
I didn't think it would work, but it did. Just put the format you like into the string xml file for me it was:
<string name="date_time_format">dd MMMM yyyy, hh.mm a</string>
<string name="date_time_format">dd.MM.yyyy, HH:mm</string>
然后像这样在SDF中使用它:
Then use it in the SDF like this:
SimpleDateFormat fmtOut = new SimpleDateFormat(context.getString(R.string.date_time_format), Locale.getDefault());
对于德语格式末尾的"Uhr",我添加了一个如下所示的占位符字符串:
for the "Uhr" at the end of the german format i added a placeholder String that looks like this:
<string name="date_time_string">%s</string>
<string name="date_time_string">%s Uhr</string>
我用String.format()方法返回格式化的日期:
and i return the formated date with the String.format() method:
return String.format(context.getString(R.string.date_time_string), fmtOut.format(date));
这篇关于根据语言使用不同的时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!