【问题标题】:How to get Timezone from String in JAVA如何从 JAVA 中的字符串获取时区
【发布时间】:2019-02-05 17:57:14
【问题描述】:

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

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


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

   static DateTimeZone forOffsetHoursMinutes(int hoursOffset, int minutesOffset) 

不确定这是否理想。

2) 我检查了 Timezone 类。

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.

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

【问题讨论】:

标签: java timezone jodatime


【解决方案1】:

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

TimeZone 类中有一个名为getTimeZone(String id) 的方法,您可以在其中传入一个字符串,可以是"GMT-04:00"。你应该检查一下。

请务必尝试几个示例并确保正确使用它。其中一些默认方法需要特定的格式。

【讨论】:

  • @webExplorer 所以当你调用getTimeZone(String id) 方法时,你会得到一个TimeZone 对象。使用此对象,您可以调用getDisplayName(Boolean.TRUE, 0) 方法。现在,第一个输入是一个布尔值,它指定是否存在夏令时。第二个输入是显示名称应该是短的(如 PST,使用 0)还是长(太平洋标准时间,使用 1)。查看我原始答案中的 API,会有更多详细信息。
  • 感谢您的回答.. 我已经检查过了.. 但我不确定要为 getTimeZone 函数传递什么 ID。如果你观察到,我传递给函数的任何值都会返回 GMT。
  • @webExplorer 啊,我明白了。除此之外我真的不知道,但我发现了一个类似的线程,不确定你是否已经看过这个:stackoverflow.com/questions/4869206/…
猜你喜欢
  • 2021-07-14
  • 2015-03-11
  • 2019-01-13
  • 2016-05-13
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 1970-01-01
  • 2023-02-21
相关资源
最近更新 更多