如何将日期字符串 (2021-01-13) 转换为 '2020-01-13T00:00:00.000-4:00' 格式而不会丢失秒、微秒

时间:2021-05-17 12:13:11

标签: java java-time

我使用以下代码将字符串转换为所需的格式。但在输出秒中,缺少微秒。

LocalDate date = LocalDat.parse(inputString, DateTimeFormatter.ISO_LOCAL_DATE);
date.atStartOfDay(ZooneId.of("America/New_York").toOffsetDateTime().toString();

基于上述代码的输出:'2021-01-13T00:00-4:00'

所需输出:'2020-01-13T00:00:00.000-4:00'

1 个答案:

答案 0 :(得分:2)

您可以使用 format() 方法进一步重新格式化。

LocalDate date = LocalDate.parse("2021-01-13", DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(date.atStartOfDay(ZoneId.of("America/New_York")).toOffsetDateTime().format(DateTimeFormatter.ofPattern(("yyyy-MM-dd'T'HH:mm:ss:SSSZ"))));

在此处查看可用日期格式的完整列表 https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

相关问题