spring boot中的日期转换

问题描述 投票:0回答:1

我在spring boot中格式化日期格式,但是它也在改变日期的timeZone。它自己增加了 5.30 小时,这是我不想要的。这是我的片段。请帮我找到一种方法来转换格式而不转换时区。

                String startTime = searchParams.getDeploymentStartDate();
                String endTime = searchParams.getDeploymentEndDate();
                System.out.println("startTime from req body in utc:"+startTime);

                DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd' HH:mm:ss", Locale.ENGLISH).ISO_OFFSET_DATE_TIME;

                Date startDate = Date.from(ZonedDateTime.parse(startTime, targetFormatter).toInstant());
                Date endDate = Date.from((ZonedDateTime.parse(endTime, targetFormatter).toInstant()));
                System.out.println("startDate converted to desired format in IST:"+startDate);

实际产量:

startTime from req body in utc:2023-03-22T11:27:04Z
startDate converted to desired format in IST:Wed Mar 22 16:57:04 IST 2023 

期望的输出:

startTime from req body in utc:2023-03-22T11:27:04Z
startDate converted to desired format in IST:Wed Mar 22 11:27:04 IST 2023
java spring spring-boot java-time
1个回答
0
投票

请不要使用已弃用的

java.util.Date
。而是使用
java.time.LocalDateTime
java.time.ZonedDateTime
.

注意: 时间被转换并显示在您当地的时区(自动从您的计算机中选择),这也是 IST(UTC +5:30),这就是您要打印的内容,即 startDate 转换为所需格式在 IST.

因此,您案例中的实际输出是正确的。

此外,将代码(不使用

java.util.Date
)更新为:

String startTime = searchParams.getDeploymentStartDate();
System.out.println("startTime from req body in utc:" + startTime);
ZonedDateTime ist = ZonedDateTime.parse(startTime)
                .withZoneSameInstant(ZoneId.of("Asia/Kolkata"));
System.out.println("startDate converted to desired format in IST:" 
             + ist.format(DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss z u")));

输出:

startTime from req body in utc:2023-03-22T11:27:04Z
startDate converted to desired format in IST:Wed Mar 22 16:57:04 IST 2023

注意:如果您想要不同时区的时间,只需修改

ZoneId.of(...)

我提供了官方文档支持的ZoneIds列表:

EST - -05:00
HST - -10:00
MST - -07:00
ACT - Australia/Darwin
AET - Australia/Sydney
AGT - America/Argentina/Buenos_Aires
ART - Africa/Cairo
AST - America/Anchorage
BET - America/Sao_Paulo
BST - Asia/Dhaka
CAT - Africa/Harare
CNT - America/St_Johns
CST - America/Chicago
CTT - Asia/Shanghai
EAT - Africa/Addis_Ababa
ECT - Europe/Paris
IET - America/Indiana/Indianapolis
IST - Asia/Kolkata
JST - Asia/Tokyo
MIT - Pacific/Apia
NET - Asia/Yerevan
NST - Pacific/Auckland
PLT - Asia/Karachi
PNT - America/Phoenix
PRT - America/Puerto_Rico
PST - America/Los_Angeles
SST - Pacific/Guadalcanal
VST - Asia/Ho_Chi_Minh
© www.soinside.com 2019 - 2024. All rights reserved.