java.util
date-time classes are outdated and error-prone and so is their formatting API, SimpleDateFormat
. I suggest you should stop using them completely and switch to the modern date-time API.
If you are doing it for your Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Learn more about the modern date-time API at Trail: Date Time.
Using the modern date-time 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
Using the legacy API:
Note that Z
in the date-time stands for Zulu
time (0-hour offset) and 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