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

时间:2019-02-04 18:45:41

标签: java utc date-formatting datetimeoffset

我正在尝试将日期字符串从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);

输出 02/04/2019 18:17:15

1 个答案:

答案 0 :(得分:0)

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

  

指定的TimeZone或GMT区域(如果无法理解给定的ID)

无法理解"+5:30"时区,因此您会获得格林尼治标准时间。

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

02/04/2019 23:47:15

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

  

自定义时区ID的语法为:

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开头。