简体   繁体   中英

How can i convert the windows timezone to Java Timezone?

I'm getting windows time zone as input, which i want to convert it to UTC time in Java. some windows time zone are not same as Java's. For example:

Windows time zone = MPST (Malay Peninsula Standard Time) equivalent Java time zone = SGT (Singapore Standard Time) My input be like - 13/01/2020 10:46:10 MPST . so, when i'm trying to convert this date format to UTC, i'm getting java.text.ParseException: Unparseable date: "13/01/2020 10:46:10 MPST"

Please, help.

Thanks in advance

Avoid pseudo-codes for time zones

The 2-4 letter pseudo-codes often seen in the media are not actual time zones. Values such as IST , PST , CST , and your MPST are not standardized, and are not even unique!

Use only proper time zone names in the format of Continent/Region . See this possibly-outdated list at Wikipedia .

ZoneId z = ZoneId.of( "Asia/Kuala_Lumpur" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;

020-01-15T08:02:26.612494+08:00[Asia/Kuala_Lumpur]

See that code run live at IdeOne.com .

The DateTimeFormatter class will try to guess the real time zone intended by the use of a 2-4 letter pseudo-zone. For example:

String input = "13/01/2020 10:46:10 PST" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss zz") ;
ZonedDateTime zdt = ZonedDateTime.parse( input , f ) ;
System.out.println( "zdt.toString(): " + zdt ) ;

zdt.toString(): 2020-01-13T10:46:10-08:00[America/Los_Angeles]

But guessing MPST fails with a runtime error.

ISO 8601

In any such case as either PST or MPST , you really should go back to the source of the data. Educate those people about the ISO 8601 standard designed for the purpose of exchanging date-time values as text.

By the way, the toString method of the ZonedDateTime class seen above extends the ISO 8601 standard format by wisely appending the name of the time zone in square brackets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM