The zone offset for both the dates is 0800 which is CST – China Standard Time so AM/PM will be shown as 上午/下午. To prevent this, specify the default Locale using Locale.getDefault(), it returns the default locale set by the Java Virtual Machine.
You can do it like this:
import java.time.*;
import java.time.format.*;
import java.util.*;
public class StackOverflow
{
public static void main(String[] args)
{
String date = "2020-11-09T06:41:01-0800";
ZonedDateTime zdt = ZonedDateTime.parse(date,DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a",Locale.getDefault());
String formatted = formatter.format(zdt);
System.out.println(formatted);
}
}
it prints your desired result:
6:41 AM
SimpleDateFormatclass is notoriously troublesome and long outdated. It’s much better to use java.time, the modern Java date and time API.SimpleDateFormatclass which is notoriously troublesome and long outdated. It’s much better to use java.time, the modern Java date and time API.