java - 如何在 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()));
这里缺少什么,请指教?
解决方案
您的格式与您的输入不匹配,特别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是一本有趣的读物
推荐阅读
- android - TIZEN STUDIO 本地标志构建问题
- python - 谁能告诉我我的代码有什么问题,它显示(SyntaxError:无效语法)?
- java - 仅使用 Java 而非 keytool 将密钥对设置到密钥库中
- python - 用numpy的限制填充
- python - 如何使用 xlsxwriter 将我的数据表逐行写入 Excel
- json - 尝试使用 Python 解析 JSON 文件
- excel - 从一个工作表复制动态数据范围(来自数据透视表)并粘贴到另一个工作表
- r - 计算除当前组之外的所有组的平均值
- r - R对分类年龄组进行分箱
- docker - 运行 apt-get install 时出现 Dockerfile 错误