JAVA中如何从字符串中获取时区

web*_*rer 4 java timezone jodatime

我有一个输入“+04:00”

我可以使用什么 API 来获取时区?


到目前为止,1)我研究了joda - https://www.joda.org/joda-time/apidocs/org/joda/time/DateTimeZone.html

   static DateTimeZone forOffsetHoursMinutes(int hoursOffset, int minutesOffset) 
Run Code Online (Sandbox Code Playgroud)

不确定这是否理想。

2)我检查了时区类。

http://docs.oracle.com/javase/6/docs/api/java/util/TimeZone.html#getTimeZone%28java.lang.String%29

 getTimeZone

public static TimeZone getTimeZone(String ID)

    Gets the TimeZone for the given ID.

    Parameters:
        ID - the ID for a TimeZone, either an abbreviation such as "PST", a full name such as "America/Los_Angeles", or a custom ID such as "GMT-8:00". Note that the support of abbreviations is for JDK 1.1.x compatibility only and full names should be used. 
    Returns:
        the specified TimeZone, or the GMT zone if the given ID cannot be understood.
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下如何将自定义 ID 作为此函数的输入吗?

Sto*_*Man 5

http://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html

TimeZone 类中有一个方法,getTimeZone(String id)您可以在其中传递一个 String,它可以类似于"GMT-04:00". 你应该检查一下。

只要确保尝试一些示例并确保正确使用它即可。其中一些默认方法需要特定格式。