001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      https://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.lang3.time;
019
020import java.util.TimeZone;
021import java.util.regex.Matcher;
022import java.util.regex.Pattern;
023
024/**
025 * Faster methods to produce custom time zones.
026 *
027 * @since 3.7
028 */
029public class FastTimeZone {
030
031    private static final Pattern GMT_PATTERN = Pattern.compile("^(?:(?i)GMT)?([+-])?(\\d\\d?)?(:?(\\d\\d?))?$");
032
033    private static final TimeZone GREENWICH = new GmtTimeZone(false, 0, 0);
034
035    /**
036     * Gets the GMT TimeZone.
037     *
038     * @return A TimeZone with a raw offset of zero.
039     */
040    public static TimeZone getGmtTimeZone() {
041        return GREENWICH;
042    }
043
044    /**
045     * 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
046     * hours and minutes.
047     *
048     * <p>
049     * Note: the underlying regex is lenient — every capture group (sign, hours, minutes, and the {@code GMT} prefix) is optional. Inputs that lack any digit
050     * 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
051     * of zero (mirroring {@link TimeZone#getTimeZone(String)} JDK-parity for unrecognized ids). Inputs that fail the regex outright, or that match but specify
052     * an out-of-range offset (24 hours or 60 minutes and above), return {@code null}.
053     * </p>
054     *
055     * @param pattern The GMT offset.
056     * @return A TimeZone matching the (possibly partial or empty) GMT offset pattern, defaulting to GMT for an unrecognized but parseable input, or
057     *         {@code null} if the pattern fails the regex or specifies an out-of-range offset.
058     */
059    public static TimeZone getGmtTimeZone(final String pattern) {
060        if ("Z".equals(pattern) || "UTC".equals(pattern)) {
061            return GREENWICH;
062        }
063        final Matcher m = GMT_PATTERN.matcher(pattern);
064        if (m.matches()) {
065            final int hours = parseInt(m.group(2));
066            final int minutes = parseInt(m.group(4));
067            if (hours == 0 && minutes == 0) {
068                return GREENWICH;
069            }
070            if (hours >= 24 || minutes >= 60) {
071                // A matching but out-of-range offset is not a valid GMT id; report it the documented
072                // way instead of letting the GmtTimeZone constructor throw IllegalArgumentException.
073                return null;
074            }
075            return new GmtTimeZone(parseSign(m.group(1)), hours, minutes);
076        }
077        return null;
078    }
079
080    /**
081     * 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
082     * GMT, followed by sign, hours digit(s), optional colon(':'), and optional minutes digits. i.e. <em>[GMT] (+|-) Hours [[:] Minutes]</em>
083     *
084     * @param id A GMT custom id or Olson id.
085     * @return A time zone.
086     */
087    public static TimeZone getTimeZone(final String id) {
088        final TimeZone tz = getGmtTimeZone(id);
089        return tz != null ? tz : TimeZones.getTimeZone(id);
090    }
091
092    private static int parseInt(final String s) {
093        return s != null ? Integer.parseInt(s) : 0;
094    }
095
096    private static boolean parseSign(final String group) {
097        return group != null && group.charAt(0) == '-';
098    }
099
100    // do not instantiate
101    private FastTimeZone() {
102    }
103
104}