Android:如何根据设备时区获取默认的日期格式

huangapple go评论66阅读模式
英文:

Android: how to get the default date format based on device timezone

问题

有没有一种简单的方法来获取用户时区的默认日期格式?

SimpleDateFormat()根据用户的区域设置提供日期格式。我正在寻找一种情况,我需要将提供的日期转换为基于时区的日期格式。

例如,用户将她的区域设置为“中文”,而在德国时区应该以日期格式dd.mm.yyyy显示。

英文:

Is there any simple way to fetch the default date format as per user's timezone?

The SimpleDateFormat() gives the date format as per the user locale. I'm in search of a scenario where I need to convert a supplied Date into timezone based date format.

Say e.g., A user set her locale as 'Chinese' and in German timezone should result in the date format as dd.mm.yyyy

答案1

得分: 3

你可以按照以下方式进行操作:

  1. 使用地理位置 API获取国家代码,例如通过解析来自网址http://ip-api.com/json 的JSON,您可以获得国家代码。

  2. 循环遍历Locale.getAvailableLocales(),假设使用循环变量locale,并返回locale,其中locale.getCountryCode().equals(从JSON中获取的国家代码)

  3. 使用获得的Locale,获取日期模式,如下所示:

     String datePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT, null,
                     IsoChronology.INSTANCE, locale);
    
英文:

You can do it as follows:

  1. Use a Geolocation API to get the country code e.g by parsing the JSON from the URL, http://ip-api.com/json you can get the country code.

  2. Loop through Locale.getAvailableLocales(), let's say using the loop variable, locale and return the locale for which locale.getCountryCode().equals(the-country-code-obtained-from-the-json)

  3. With the obtained Locale, get the date pattern as shown below:

    String datePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT, null,
                        IsoChronology.INSTANCE, locale);
    

答案2

得分: 1

尝试这个来获取设备上的日期格式:

Format dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
String pattern = ((SimpleDateFormat) dateFormat).toLocalizedPattern();
英文:

Try this to fetch dateformat from device:

Format dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
String pattern = ((SimpleDateFormat) dateFormat).toLocalizedPattern();

huangapple
  • 本文由 发表于 2020年9月8日 19:57:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63793425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定