首页 > 解决方案 > 如何在 java -simpledateformat 中将 UTC 日期转换为 PST 日期

问题描述

我正在尝试使用 simpledateformat 函数,但我不断收到错误为“无法解析的日期:”

当前存储在string testtime=2021-09-14T21:15:09.863Z;//UTC 时间中的时间我想使用 T 和 Z 表示法将其转换为相同格式的 PST 时间;

Date date1=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm.sss'Z'").parse(testtime); 

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm.sss'Z", Locale.US);

 dateFormat.setTimeZone(TimeZone.getTimeZone("PST"));

System.out.println("PRINTING the TIME in PST"+dateFormat.format(date1.getTime()));

这里缺少什么,请指教?

标签: javatimezonetalendsimpledateformatutc

解决方案


您的格式与您的输入不匹配,特别HH:mm.sss是不匹配21:15:09.863

将格式更改为HH:mm:ss.SSS

然后开始使用较新的日期/时间 API(即java.time

Java 8+

String dateInString = "2021-09-14T21:15:09.863Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");

OffsetDateTime odt = OffsetDateTime.parse(dateInString, formatter);

ZoneId utcTZId = ZoneId.of("Etc/UTC");
ZonedDateTime utcDT = odt.atZoneSameInstant(utcTZId);
System.out.println(utcDT.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));

ZoneId laTZId = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime laDT = utcDT.withZoneSameInstant(laTZId);
System.out.println(laDT.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));

哪个打印...

2021-09-14T21:15:09.863Z[Etc/UTC]
2021-09-14T14:15:09.863-07:00[America/Los_Angeles]

Java Convert UTC to PDT/PST with Java 8 time library是一本有趣的读物


推荐阅读