在 Android Studio 中更改日期格式

Change DateFormat in Android Studio

我有来自 API 的数据,数据的日期格式为 "2018-07-09"。如何在 android studio 中将格式更改为 Monday, July 9 , 2018

您可以解析字符串以反对它们使用 DateTimeFormatter:

格式化
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, MMMM d, yyyy", Locale.ENGLISH);
System.out.println(formatter.format(parser.parse( "2018-07-09"))); // Monday, July 9, 2018
SimpleDateFormat fromApi = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat myFormat = new SimpleDateFormat("EEEE, MMMM d, yyyy");

try {

    String reformattedStr = myFormat.format(fromApi.parse(inputString));
} catch (ParseException e) {
    e.printStackTrace();
}

请参阅 oracle doc 了解更多信息。

    DateTimeFormatter dateFormatter = DateTimeFormatter
            .ofLocalizedDate(FormatStyle.FULL)
            .withLocale(Locale.US);
    LocalDate date = LocalDate.parse("2018-07-09");
    String formattedDate = date.format(dateFormatter);
    System.out.println(formattedDate);

这会打印:

Monday, July 9, 2018

消息:

  • 您从 API、2018-07-09 获得的日期字符串采用 ISO 8601 格式。 LocalDate 来自 java.time,现代 Java 日期和时间 API,将此格式解析为默认格式,即没有任何显式格式化程序。所以不要费心去创建一个。
  • 为了向用户显示,请使用内置格式。您可以从 DateTimeFormatter.ofLocalizedXxxx 方法中获取它们,并可以使它们适应用户的语言环境,如上面的代码所示。
  • 您将您的问题标记为 simpledateformat。 SimpleDateFormat class 早已过时并且出了名的麻烦,所以请避免使用它。 java.time 更好用。

问题:我可以在 Android 上使用 java.time 吗?

是的,java.time 在新旧 Android 设备上都能很好地工作。它只需要至少 Java 6.

  • 在 Java 8 和更高版本以及较新的 Android 设备上(据我所知,来自 API 级别 26)现代 API 是内置的。
  • 在 Java 6 和 7 中获取 ThreeTen Backport,新 classes 的 backport(ThreeTen 用于 JSR 310;请参阅底部的链接)。
  • 在(较旧的)Android 使用 ThreeTen Backport 的 Android 版本。它叫做 ThreeTenABP。并确保使用子包从 org.threeten.bp 导入日期和时间 classes。

链接