您可以使用ThreeTen Backport,而不是直接使用SimpleDateFormat(因为这个旧API 有lots of problems 和design issues),它是Java 8 新日期/时间类的一个很好的反向移植。要在 Android 中使用它,您还需要ThreeTenABP(详细了解如何使用它here)。
要使用的主要类是org.threeten.bp.ZonedDateTime(可以解析日期/时间输入)和org.threeten.bp.format.DateTimeFormatter(控制输出格式)。
如果您将此字段 (2017-06-22T16:18:04Z) 读取为 String,则可以像这样创建 ZonedDateTime:
ZonedDateTime z = ZonedDateTime.parse("2017-06-22T16:18:04Z");
如果您已经有一个java.util.Date 对象,您可以使用org.threeten.bp.DateTimeUtils 和org.threeten.bp.ZoneOffset 来转换它:
Date date = // get java.util.Date
ZonedDateTime z = DateTimeUtils.toInstant(date).atZone(ZoneOffset.UTC);
最后,ZonedDateTime 对象将具有 webPublicationDate 值。
要获得不同的输出格式,只需为每种格式创建一个DateTimeFormatter。在下面的示例中,我还使用java.util.Locale 类来确保月份名称为英文:
// for Mar 3, 1984
DateTimeFormatter f1 = DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.ENGLISH);
// for 4:40 PM
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
// for 16:18
DateTimeFormatter f3 = DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH);
System.out.println(f1.format(z)); // Jun 22, 2017
System.out.println(f2.format(z)); // 4:18 PM
System.out.println(f3.format(z)); // 16:18
输出是:
2017 年 6 月 22 日
下午 4 点 18 分
16:18
请注意,它使用 UTC 时区(2017-06-22T16:18:04Z 中的 Z)。如果您想在另一个时区显示日期和时间,只需使用org.threeten.bp.ZoneId 类:
System.out.println(f3.format(z.withZoneSameInstant(ZoneId.of("Europe/London")))); // 17:18
输出是17:18(因为伦敦现在是夏季时间)。
请注意,API 使用IANA timezones names(始终采用Continent/City 格式,如America/Sao_Paulo 或Europe/Berlin)。
避免使用三个字母的缩写(如CST 或PST),因为它们是ambiguous and not standard。要找到更适合每个地区的时区,请使用 ZoneId.getAvailableZoneIds() 方法并检查哪一个最适合您的用例。
如果您不想在项目中添加另一个依赖项并使用SimpleDateFormat,您可以执行类似的操作(创建一个解析器和 3 个输出格式化程序,并使用英语语言环境)。另外不要忘记设置时区 - 我在下面使用 UTC,但您可以将其更改为您想要的任何时区。
// parse date
String dateInString = "2017-06-22T16:18:04Z";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = parser.parse(dateInString);
// create output formatters (set timezone to UTC)
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat s1 = new SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH);
s1.setTimeZone(utc);
SimpleDateFormat s2 = new SimpleDateFormat("h:mm a", Locale.ENGLISH);
s2.setTimeZone(utc);
SimpleDateFormat s3 = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
s3.setTimeZone(utc);
System.out.println(s1.format(date));
System.out.println(s2.format(date));
System.out.println(s3.format(date));
输出将是相同的:
2017 年 6 月 22 日
下午 4 点 18 分
16:18