根据区域设置显示日期

Show date based on the locale settings

我正在开发一个能够获取 post 的时间信息的应用程序。

我想要的是将以毫秒为单位的时间显示为日期以使其用户友好,但我需要注意 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,用户也不要更改应显示的方式。

谢谢

您好,使用 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 ...

java.time

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

详情见 from a nearly identical Question,

简短的示例代码,将给定输入的 long 数字变量的误称 tweetsCreatedTime 更改为 tweetMillisecondsSinceEpoch。请注意,虽然您的输入以毫秒为单位,但 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-05-23

我用DateFormat:

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

请记住,它也 returns class 命名为 java.text.DateFormat,但它 不同 class