【发布时间】:2021-07-05 03:45:13
【问题描述】:
预期输出:2021-04-05T00:00-07:00[UTC-07:00]
String sDate1="05/04/2021";
Date date=new SimpleDateFormat("M/d/yyyy").parse(sDate1);
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String text = sdf.format(date);
System.out.println("sdf: "+text);
ZonedDateTime d = ZonedDateTime.ofInstant(date.toInstant(),
ZoneId.systemDefault());
ZonedDateTime zdt= ZonedDateTime.ofInstant(date.toInstant(), ZoneId.of("UTC"));
System.out.println("zdt: "+ d);
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
ZonedDateTime result = ZonedDateTime.parse(""+d, formatter);
System.out.println("zdt result :: "+result);
输出:
sdf: 2021-04-05T00:00:00.000+05:30
zdt: 2021-04-05T00:00+05:30[Asia/Calcutta]
zdt result :: 2021-04-05T00:00+05:30[Asia/Calcutta]
但预期输出是这种格式2021-04-05T00:00-07:00[UTC-07:00]
【问题讨论】:
-
我建议你不要使用
SimpleDateFormat和Date。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。您已经在使用来自java.time, the modern Java date and time API 的ZonedDateTime和DateTimeFormatter。坚持使用该 API 并避免不必要的转换。