如何使用 timeoffset 更改日期字符串的时间格式

How to Change time format of date string using timeoffset

我正在尝试将日期字符串从 Java 中的另一个时区转换为 UTC 格式。我们只有时区偏移量,如“-06:00”。任何人都可以帮助我如何使用时区偏移将日期时间转换为 UTC 格式。

谢谢

这适用于 java 版本 1.7。我尝试使用以下代码片段,但接收到与输出相同的输入。

String dateInString = "02/04/2019 18:17:15";                
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = formatter.parse(dateInString);          
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");             
dateFormat.setTimeZone(TimeZone.getTimeZone("+5:30"));
String dateStr = dateFormat.format(date);
System.out.println(dateStr);

输出 2019 年 2 月 4 日 18:17:15

不幸的是,TimeZone.getTimeZone(String ID) returns:

the specified TimeZone, or the GMT zone if the given ID cannot be understood.

无法理解 "+5:30" 时区,因此您使用 GMT。

更改为 "GMT+5:30" 将使您的代码工作,即它会打印:

02/04/2019 23:47:15

有关有效的 ID 语法,请参阅 TimeZone 的 javadoc:

The syntax of a custom time zone ID is:

CustomID:
        GMT Sign Hours : Minutes
        GMT Sign Hours Minutes
        GMT Sign Hours
Sign: one of
        + -
Hours:
        Digit
        Digit Digit
Minutes:
        Digit Digit
Digit: one of
        0 1 2 3 4 5 6 7 8 9

如您所见,它必须始终以 GMT 开头。