How to Change time format of date string using timeoffset [duplicate]

筅森魡賤 提交于 2019-12-12 01:22:06

问题


I am trying to convert date string to UTC format from another time zone in Java. we have only time zone offset like "-06:00". Can any one help me how to convert the date time to UTC format using time zone offset.

Thanks

This for java version 1.7 . I have tried with following snippet but receiving the same input as output.

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);

Output 02/04/2019 18:17:15


回答1:


Unfortunately, TimeZone.getTimeZone(String ID) returns:

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

The "+5:30" time zone cannot be understood, so you get GMT.

Change to "GMT+5:30" will make your code work, i.e. it'll print:

02/04/2019 23:47:15

See the javadoc of TimeZone for valid ID syntax:

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

As you can see, it must always start with GMT.



来源:https://stackoverflow.com/questions/54522443/how-to-change-time-format-of-date-string-using-timeoffset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!