替换代码0】的日期时间类已经过时且容易出错,其格式化API也是如此,SimpleDateFormat
。我建议你应该完全停止使用它们,改用现代日期-时间API.
如果你正在为你的安卓项目做这件事,而你的安卓API级别仍然不符合Java-8的要求,请检查通过解ugaring提供的Java 8+ APIs和如何在Android项目中使用ThreeTenABP.
Learn more about the 现代日期-时间API at 路径:日期 时间.
Using the 现代日期-时间API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
System.out.println(formatDateStr("2020-09-23T13:45:13.371Z"));
static String formatDateStr(String strDate) {
return OffsetDateTime.parse(strDate).format(DateTimeFormatter.ofPattern("EEEE, MMMM d, uuuu", Locale.ENGLISH));
Output:
Wednesday, September 23, 2020
使用传统的API。
Note that Z
in the date-time stands for Zulu
time (0-hour offset)和therefore make sure to set the time-zone to UTC
.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
System.out.println(formatDateStr("2020-09-23T13:45:13.371Z"));
static String formatDateStr(String strDate) throws ParseException {
DateFormat inputFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
inputFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy", Locale.ENGLISH);
return outputFormatter.format(inputFormatter.parse(strDate));
Output:
Wednesday, September 23, 2020