View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.lang3.time;
19  
20  import java.util.TimeZone;
21  import java.util.regex.Matcher;
22  import java.util.regex.Pattern;
23  
24  /**
25   * Faster methods to produce custom time zones.
26   *
27   * @since 3.7
28   */
29  public class FastTimeZone {
30  
31      private static final Pattern GMT_PATTERN = Pattern.compile("^(?:(?i)GMT)?([+-])?(\\d\\d?)?(:?(\\d\\d?))?$");
32  
33      private static final TimeZone GREENWICH = new GmtTimeZone(false, 0, 0);
34  
35      /**
36       * Gets the GMT TimeZone.
37       *
38       * @return A TimeZone with a raw offset of zero.
39       */
40      public static TimeZone getGmtTimeZone() {
41          return GREENWICH;
42      }
43  
44      /**
45       * Gets a TimeZone with GMT offsets. A GMT offset must be either 'Z', or 'UTC', or match <em>(GMT)? hh?(:?mm?)?</em>, where h and m are digits representing
46       * hours and minutes.
47       *
48       * <p>
49       * Note: the underlying regex is lenient — every capture group (sign, hours, minutes, and the {@code GMT} prefix) is optional. Inputs that lack any digit
50       * group, such as the empty string, {@code "+"}, {@code "-"}, or {@code "GMT"} alone, still match and the method returns the GMT TimeZone with a raw offset
51       * of zero (mirroring {@link TimeZone#getTimeZone(String)} JDK-parity for unrecognized ids). Inputs that fail the regex outright, or that match but specify
52       * an out-of-range offset (24 hours or 60 minutes and above), return {@code null}.
53       * </p>
54       *
55       * @param pattern The GMT offset.
56       * @return A TimeZone matching the (possibly partial or empty) GMT offset pattern, defaulting to GMT for an unrecognized but parseable input, or
57       *         {@code null} if the pattern fails the regex or specifies an out-of-range offset.
58       */
59      public static TimeZone getGmtTimeZone(final String pattern) {
60          if ("Z".equals(pattern) || "UTC".equals(pattern)) {
61              return GREENWICH;
62          }
63          final Matcher m = GMT_PATTERN.matcher(pattern);
64          if (m.matches()) {
65              final int hours = parseInt(m.group(2));
66              final int minutes = parseInt(m.group(4));
67              if (hours == 0 && minutes == 0) {
68                  return GREENWICH;
69              }
70              if (hours >= 24 || minutes >= 60) {
71                  // A matching but out-of-range offset is not a valid GMT id; report it the documented
72                  // way instead of letting the GmtTimeZone constructor throw IllegalArgumentException.
73                  return null;
74              }
75              return new GmtTimeZone(parseSign(m.group(1)), hours, minutes);
76          }
77          return null;
78      }
79  
80      /**
81       * Gets a TimeZone, looking first for GMT custom ids, then falling back to Olson ids. A GMT custom id can be 'Z', or 'UTC', or has an optional prefix of
82       * GMT, followed by sign, hours digit(s), optional colon(':'), and optional minutes digits. i.e. <em>[GMT] (+|-) Hours [[:] Minutes]</em>
83       *
84       * @param id A GMT custom id or Olson id.
85       * @return A time zone.
86       */
87      public static TimeZone getTimeZone(final String id) {
88          final TimeZone tz = getGmtTimeZone(id);
89          return tz != null ? tz : TimeZones.getTimeZone(id);
90      }
91  
92      private static int parseInt(final String s) {
93          return s != null ? Integer.parseInt(s) : 0;
94      }
95  
96      private static boolean parseSign(final String group) {
97          return group != null && group.charAt(0) == '-';
98      }
99  
100     // do not instantiate
101     private FastTimeZone() {
102     }
103 
104 }