android上基于用户语言环境的日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11093182/
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
Date formatting based on user locale on android
提问by shailbenq
I want to display a date of birth based on the user locale. In my application, one of my fields is the date of birth, which is currently in the format dd/mm/yyyy
. So if the user changes his locale, the date format should also change accordingly. Any pointers or code samples would really help me to overcome the problem.
我想根据用户语言环境显示出生日期。在我的申请中,我的字段之一是出生日期,目前格式为dd/mm/yyyy
. 因此,如果用户更改其语言环境,日期格式也应相应更改。任何指针或代码示例都会真正帮助我克服这个问题。
回答by Arnaud
You can use the DateFormatclass that formats a date according to the user locale.
您可以使用根据用户区域设置格式化日期的DateFormat类。
Example:
例子:
String dateOfBirth = "26/02/1974";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = null;
try {
date = sdf.parse(dateOfBirth);
} catch (ParseException e) {
// handle exception here !
}
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context);
String s = dateFormat.format(date);
You can use the different methods getLongDateFormat
, getMediumDateFormat
depending on the level of verbosity you would like to have.
您可以使用不同的方法getLongDateFormat
,getMediumDateFormat
具体取决于您想要的详细程度。
回答by Felipe R. Saruhashi
To change the date format according to the locale, the following code worked to me:
要根据语言环境更改日期格式,以下代码对我有用:
String dateOfBirth = "26/02/1974";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = null;
try {
date = sdf.parse(dateOfBirth);
} catch (ParseException e) {
// handle exception here !
}
String myString = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
Then when you change the locale, the date format will change based on it. For more information about the dates patterns: http://docs.oracle.com/javase/tutorial/i18n/format/dateFormat.html
然后当您更改区域设置时,日期格式将根据它更改。有关日期模式的更多信息:http: //docs.oracle.com/javase/tutorial/i18n/format/dateFormat.html
回答by Ole V.V.
While the accepted answer was correct when the question was asked, it has later become outdated. I am contributing the modern answer.
虽然在提出问题时接受的答案是正确的,但后来已经过时了。我正在贡献现代答案。
java.time and ThreeTenABP
java.time 和 ThreeTenABP
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
LocalDate dateOfBirth = LocalDate.of(1991, Month.OCTOBER, 13);
String formattedDob = dateOfBirth.format(dateFormatter);
System.out.println("Born: " + formattedDob);
It gives different output depending on the locale setting of the JVM (usually taking from the device). For example:
它根据 JVM 的区域设置(通常从设备获取)提供不同的输出。例如:
- Canadian French:
Born: 91-10-13
- Chinese:
Born: 1991/10/13
- German:
Born: 13.10.91
- Italian:
Born: 13/10/91
- 加拿大法语:
Born: 91-10-13
- 中国人:
Born: 1991/10/13
- 德语:
Born: 13.10.91
- 意大利语:
Born: 13/10/91
If you want a longer format, you may specify a different format style. Example outputs in US English locale:
如果您想要更长的格式,您可以指定不同的格式样式。美国英语语言环境中的示例输出:
FormatStyle.SHORT
:Born: 10/13/91
FormatStyle.MEDIUM
:Born: Oct 13, 1991
FormatStyle.LONG
:Born: October 13, 1991
FormatStyle.FULL
:Born: Thursday, October 13, 1991
FormatStyle.SHORT
:Born: 10/13/91
FormatStyle.MEDIUM
:Born: Oct 13, 1991
FormatStyle.LONG
:Born: October 13, 1991
FormatStyle.FULL
:Born: Thursday, October 13, 1991
Question: Can I use java.time on Android?
问题:我可以在 Android 上使用 java.time 吗?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
是的,java.time 在较旧和较新的 Android 设备上都能很好地工作。它只需要至少Java 6。
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It's called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
- 在 Java 8 及更高版本和更新的 Android 设备(从 API 级别 26)中,现代 API 是内置的。
- 在 Java 6 和 7 中获得 ThreeTen Backport,现代类的 backport(ThreeTen for JSR 310;请参阅底部的链接)。
- 在(较旧的)Android 上使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。并确保从
org.threeten.bp
子包中导入日期和时间类。
Question: Can I also accept user input in the user's local format?
问题:我也可以接受用户本地格式的用户输入吗?
Yes, you can. The formatter can also be used for parsing a string from the user into a LocalDate
:
是的你可以。格式化程序还可用于将来自用户的字符串解析为LocalDate
:
LocalDate date = LocalDate.parse(userInputString, dateFormatter);
I suggest that you first format an example date and show it to the user so that s/he can see which format your program expects for his/her locale. As example date take a date with day of month greater than 12 and year greater than 31 so that the order of day, month and year can be seen from the example (for longer formats the year doesn't matter since it will be four digits).
我建议您首先格式化一个示例日期并将其显示给用户,以便他/她可以看到您的程序期望他/她的语言环境使用哪种格式。作为示例日期,日期大于 12,年份大于 31,以便可以从示例中看到日、月和年的顺序(对于更长的格式,年份无关紧要,因为它将是四位数)。
Parsing will throw a DateTimeParseException
if the user entered the date in an incorrect format or a non-valid date. Catch it and allow the user to try again.
DateTimeParseException
如果用户输入的日期格式不正确或日期无效,解析将抛出。抓住它并允许用户再试一次。
Question: Can I do likewise with a time of day? A date and time?
问题:我可以用一天中的某个时间做同样的事情吗?日期和时间?
Yes. For formatting a time of day according to a user's locale, get a formatter from DateTimeFormatter.ofLocalizedTime
. For both date and time together use one of the overloaded versions of DateTimeFormatter.ofLocalizedDateTime
.
是的。要根据用户的语言环境格式化一天中的时间,请从DateTimeFormatter.ofLocalizedTime
. 对于日期和时间,一起使用DateTimeFormatter.ofLocalizedDateTime
.
Avoid the DateFormat, SImpleDateFormat and Date classes
避免使用 DateFormat、SImpleDateFormat 和 Date 类
I recommend you don't use DateFormat
, SimpleDateFormat
and Date
. Those classes are poorly designed and long outdated, the first two in particular notoriously troublesome. Instead use LocalDate
, DateTimeFormatter
and other classes from java.time, the modern Java date and time API.
我建议您不要使用DateFormat
,SimpleDateFormat
和Date
。这些类的设计很差,而且已经过时了,尤其是前两个类是出了名的麻烦。而是使用LocalDate
,DateTimeFormatter
和 java.time 中的其他类,现代 Java 日期和时间 API。
Links
链接
- Oracle tutorial: Date Timeexplaining how to use java.time.
- Java Specification Request (JSR) 310, where
java.time
was first described. - ThreeTen Backport project, the backport of
java.time
to Java 6 and 7 (ThreeTen for JSR-310). - ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
- Oracle 教程:解释如何使用 java.time 的日期时间。
- Java 规范请求 (JSR) 310,
java.time
首先描述的地方。 - ThreeTen Backport 项目,
java.time
向 Java 6 和 7 (ThreeTen for JSR-310)的向后移植。 - ThreeTenABP, ThreeTen Backport安卓版
- 问题:如何在Android项目中使用ThreeTenABP,讲解很透彻。
回答by David_E
As simple as
就这么简单
For date + time:
对于日期 + 时间:
DateFormat format = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, Locale.getDefault());
For just date:
仅日期:
DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
回答by Justin Song
Android api provide easy way to display localized date format. The following code works.
Android api 提供了显示本地化日期格式的简单方法。以下代码有效。
public class FileDateUtil {
public static String getModifiedDate(long modified) {
return getModifiedDate(Locale.getDefault(), modified);
}
public static String getModifiedDate(Locale locale, long modified) {
SimpleDateFormat dateFormat = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
dateFormat = new SimpleDateFormat(getDateFormat(locale));
} else {
dateFormat = new SimpleDateFormat("MMM/dd/yyyy hh:mm:ss aa");
}
return dateFormat.format(new Date(modified));
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public static String getDateFormat(Locale locale) {
return DateFormat.getBestDateTimePattern(locale, "MM/dd/yyyy hh:mm:ss aa");
}
}
You can check following code.
您可以检查以下代码。
String koreaData = FileDateUtil.getModifiedDate(Locale.KOREA, System.currentTimeMillis());
String franceData = FileDateUtil.getModifiedDate(Locale.FRENCH, System.currentTimeMillis());
String defaultData = FileDateUtil.getModifiedDate(Locale.getDefault(), System.currentTimeMillis());
String result = "Korea : " + koreaData + System.getProperty("line.separator");
result += "France : " + franceData + System.getProperty("line.separator");
result += "Default : " + defaultData + System.getProperty("line.separator");
tv.setText(result);
回答by manish poddar
To get the date format pattern you can do :
要获取日期格式模式,您可以执行以下操作:
Format dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
String pattern = ((SimpleDateFormat) dateFormat).toLocalizedPattern();
After that, you can format your input as per the pattern.
之后,您可以根据模式格式化您的输入。