根据区域设置显示日期

时间:2016-04-27 00:00:43

标签: android date locale

我开发的应用程序能够获取帖子的时间信息。

我想要的是以毫秒显示时间以使其用户友好,但我需要注意在Android设备的设置中定义的日期格式。

如果它是dd / mm / yyyy或mm / dd / yyyy或yyyy / dd / mm

当我能够确定格式时,我只需要获得日期和月份。一年对我来说毫无用处。

我已经完成了下面的代码,但我不喜欢我使用子字符串这一事实,因为如果01/02成为1/2,它就无法正常工作

DateFormat.getDateInstance(DateFormat.SHORT).format(new Date(tweetsCreatedTime)).substring(0,5)

tweetsCreatedTime以毫秒为单位,定义为长

不是使用本地,而是更好地获取设置并确保即使本地显示EN或US,用户也不会改变它应该显示的方式。

由于

3 个答案:

答案 0 :(得分:1)

java.time

您应该使用java.time包中的现代日期类。

有关详细信息,请参阅几乎相同的问题my Answer中的How can I format Date with Locale in Android

简短的示例代码,将给定输入的tweetsCreatedTime数字变量的误称tweetMillisecondsSinceEpoch更改为long。请注意,虽然您的输入以毫秒为单位,但java.time类实际上具有更精细的纳秒级分辨率。

Instant instant = Instant.ofEpochMilli( tweetMillisecondsSinceEpoch );  // Number of milliseconds since the POSIX epoch of first moment of 1970 in UTC. 
ZoneId zoneId = ZoneId.of( "Pacific/Auckland" );  // Arbitrary choice of time zone. Crucial it determining the date, as date varies with a new day dawning earlier to the east.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );  // Apply a time zone.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM );  // Let java.time translate human language and determine cultural norms in formatting.
formatter = formatter.withLocale( Locale.CANADA_FRENCH );  // Arbitrarily choosing Québec as the Locale. Note that Locale has *nothing* to do with time zone. You could use Chinese locale for a time zone in Finland. 
String output = zdt.format( formatter );  // Generate String representation of our date-time value.
  

2015年5月23日

答案 1 :(得分:1)

我使用DateFormat

java.text.DateFormat dateFormat = DateFormat.getTimeFormat(context);
String dateString = dateFormat.format(date);

请记住,它还会返回名为java.text.DateFormat的类,但它是不同的类

答案 2 :(得分:0)

嗨使用SimpleDateFormater它允许使用你自己的格式与任何日期,无论设备设置在这里是一个自定义的方法,我使用所有时间甚至你可以设置当地你希望它显示日期

 /**
 * Get localized date string (Using given locale)
 *
 * @param dateString Date string
 * @param locale     Desired locale
 * @return Formatted localized date string
 */
public static String formatLocalized(String dateString, Locale locale) {
    Date date = formatDate(dateString, locale);
    SimpleDateFormat iso8601Format = new SimpleDateFormat("d MMM yyyy", locale);
    iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC"));
    return iso8601Format.format(date);

}

使用Locale.ENGLISH | Locale.FRENCH ...

定义本地
相关问题