TimeZonePickerUtils.java revision cc955106e2889ec351593b913cb7af4328dca153
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.timezonepicker;
18
19import android.text.format.DateUtils;
20import android.text.format.Time;
21
22import java.util.Locale;
23import java.util.TimeZone;
24
25public class TimeZonePickerUtils {
26
27    /**
28     * Given a timezone id (e.g. America/Los_Angeles), returns the corresponding timezone
29     * display name (e.g. (GMT-7.00) Pacific Time).
30     *
31     * @param id The timezone id
32     * @param millis The time (daylight savings or not)
33     * @return The display name of the timezone.
34     */
35    public static String getGmtDisplayName(String id, long millis) {
36        TimeZone timezone = TimeZone.getTimeZone(id);
37        if (timezone == null) {
38            return null;
39        }
40        return buildGmtDisplayName(timezone, millis);
41    }
42
43    private static String buildGmtDisplayName(TimeZone tz, long timeMillis) {
44        Time time = new Time(tz.getID());
45        time.set(timeMillis);
46
47        StringBuilder sb = new StringBuilder();
48        sb.append("(GMT");
49
50        final int gmtOffset = tz.getOffset(timeMillis);
51        if (gmtOffset < 0) {
52            sb.append('-');
53        } else {
54            sb.append('+');
55        }
56
57        final int p = Math.abs(gmtOffset);
58        sb.append(p / DateUtils.HOUR_IN_MILLIS); // Hour
59
60        final int min = (p / (int) DateUtils.MINUTE_IN_MILLIS) % 60;
61        if (min != 0) { // Show minutes if non-zero
62            sb.append(':');
63            if (min < 10) {
64                sb.append('0');
65            }
66            sb.append(min);
67        }
68        sb.append(") ");
69
70        // tz.inDaylightTime(new Date(timeMillis))
71        String displayName = tz.getDisplayName(time.isDst != 0, TimeZone.LONG,
72                Locale.getDefault());
73        sb.append(displayName);
74
75        if (tz.useDaylightTime()) {
76            sb.append(" \u2600"); // Sun symbol
77        }
78        return sb.toString();
79    }
80
81}
82