-1

我正在尝试将收到的日期时间字符串(IST 格式)转换为 UTC 格式。

String time = 124200;
String date = 05/09/21;
DateTimeFormatter parser = DateTimeFormatter.ofPattern("dd/MM/yyHHmmss").withZone(ZoneId.of("UTC")); 
String dateInString = date.concat(time);
ZonedDateTime dateTime = ZonedDateTime.parse(dateInString, parser);
return Timestamp.valueOf(dateTime.toLocalDateTime()).toString();

此代码段不会转换为 UTC。请让我知道是什么问题

4

1 回答 1

3

长话短说:您解析的时间被视为UTC,因为您附加了ZoneId.of("UTC")第一个。这意味着您在当天的那个时间就好像它是以UTC记录的一样。

相反,您应该使用IST作为原始区域:

public static void main(String[] args) {
    // time and date in IST (?)
    String time = "124200";
    String date = "05/09/21";
    // two parsers, one for date and one for time
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/uu");
    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HHmmss");
    // parse the date and time using the parsers
    LocalDate localDate = LocalDate.parse(date, dateFormatter);
    LocalTime localTime = LocalTime.parse(time, timeFormatter);
    
    /*
     * until here, there's just date and time, NO zone!
     * If you apply UTC here, the parsed date and time would be regarded as UTC!
     */
    
    // create a ZonedDateTime with the desired SOURCE zone from the date and time
    ZonedDateTime istTime = ZonedDateTime.of(localDate, localTime, ZoneId.of("Asia/Kolkata"));
    // then convert it to UTC
    ZonedDateTime utcTime = istTime.withZoneSameInstant(ZoneId.of("UTC"));
    // print the results in order to view the difference
    System.out.println(istTime);
    System.out.println(utcTime);
}

此代码片段的输出(隐式使用ZonedDateTime.toString())是

2021-09-05T12:42+05:30[Asia/Kolkata]
2021-09-05T07:12Z[UTC]

如果您的系统将IST作为其默认区域,您可以写ZoneId.systemDefault()而不是ZoneId.of("Asia/Kolkata"),但我必须在我的机器上使用显式区域,我在欧洲。

于 2021-09-20T14:46:56.840 回答