
本文介绍了如何使用 Java 8 以上版本 java.time API 将 EDT(美国东部时间)时区的日期字符串转换为 UTC(协调世界时)日期。核心是正确分析包含时区信息的日期字符串,并使用它 ZonedDateTime 类的 withZoneSameInstant 该方法将其转换为 UTC 时区。它还提供了一个详细的代码示例,显示了如何获得它 Instant、ZonedDateTime 和 LocalDateTime 类型的 UTC 时间。
在处理来自不同系统的数据时,日期和时间通常以字符串的形式表示,并可能包含时区信息。将这些日期和时间转换为统一的时区(例如 UTC)存储和处理是确保数据一致性和准确性的重要步骤。java.time API 为完成这项任务提供了强大的工具。
使用 ZonedDateTime 进行时区转换
ZonedDateTime 类是 java.time API 用于表示带时区信息的日期和时间类别。将 EDT 时区的日期字符串转换为 UTC,以下步骤:
立即学习“Java免费学习笔记(深入);
- 分析日期字符串: 使用 DateTimeFormatter 使用类定义日期字符串的格式 ZonedDateTime.parse() 该方法将字符串分析为 ZonedDateTime 对象。 确保 DateTimeFormatter 模式字符串与日期字符串的格式完全匹配,并包含时区信息(如 "z")。
- 转换为 UTC 时区: 使用 ZonedDateTime.withZoneSameInstant(ZoneId) 方法将 ZonedDateTime 对象转换为 UTC 时区。ZoneId.of("UTC") 或 ZoneOffset.UTC 用于指定 UTC 时区。
- 获取所需的时间表示: 根据需要,可以从 ZonedDateTime 对象获取 Instant、LocalDateTime 或 OffsetDateTime 类型的 UTC 时间。
代码示例
如何演示以下代码示例? "11-14-2022 10:41:12 EDT" 字符串转换为 UTC 分别以时间为准 Instant、ZonedDateTime 和 LocalDateTime 形式展示:
快转字幕
新一代 AI 字幕工作站,为创作者提供字幕制作、学习资源、会议记录、字幕制作等场景,一键为您的视频生成准确的字幕。
357
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String dateFromUpstream = "11-14-2022 10:41:12 EDT";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss z", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(dateFromUpstream, dtf);
Instant instant = zdt.toInstant();
System.out.println("Instant (UTC): " + instant);
// Or get a ZonedDateTime at UTC
ZonedDateTime zdtUTC = zdt.withZoneSameInstant(ZoneOffset.UTC);
System.out.println("ZonedDateTime (UTC): " + zdtUTC);
// If you want LocalDateTime
LocalDateTime ldt = zdtUTC.toLocalDateTime();
System.out.println("LocalDateTime (UTC): " + ldt);
// OffsetDateTime at UTC
OffsetDateTime odtUTC = zdt.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC);
System.out.println("OffsetDateTime (UTC): " + odtUTC);
}
}
输出结果
Instant (UTC): 2022-11-14T15:41:12Z ZonedDateTime (UTC): 2022-11-14T15:41:12Z LocalDateTime (UTC): 2022-11-14T15:41:12 OffsetDateTime (UTC): 2022-11-14T15:41:12Z
注意事项
- DateTimeFormatter 模式字符串必须与日期字符串的格式完全匹配。 如果格式不匹配,将被抛出 DateTimeParseException 异常。 使用 Locale.ENGLISH 确保时区名称(例如 "EDT")正确分析。
- 时区名称的分析取决于系统配置。 在某些情况下,可能需要提供更具体的时区 ID,例如 "America/New_York而不是使用缩写 "EDT"。
- Instant 表示时间轴上的瞬时点,不包含时区信息。 ZonedDateTime 和 OffsetDateTime 它包含时区信息。 LocalDateTime 它不包含时区信息,因此在存储和处理时需要特别小心,以确保它总是代表 UTC 时间。
总结
使用 java.time API 将带时区信息的日期字符串转换为带时区信息的日期字符串可以很容易地 UTC 时间。 日期字符串的正确分析和使用 ZonedDateTime 类的 withZoneSameInstant 可以获得方法 Instant、ZonedDateTime 或 LocalDateTime 类型的 UTC 时间。 在处理日期和时间时,一定要注意时区信息,选择合适的时间表示,以保证数据的一致性和准确性.
以上是Java 中将 EDT 时区日期字符串转换为 UTC 详情请关注图灵教育的其他相关文章!
相关标签:
java 工具 ai stream 字符串解析 yy Java 字符串 对象