aboutsummaryrefslogtreecommitdiffstats
path: root/server/src/main/java/com/vaadin/util/TimeZoneUtil.java
blob: c3c25b21e45209b4b308f9ff9680ecea33774726 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/*
 * Copyright 2000-2016 Vaadin Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.vaadin.util;

import java.io.Serializable;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.zone.ZoneOffsetTransition;
import java.time.zone.ZoneRules;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import elemental.json.JsonArray;
import elemental.json.JsonObject;
import elemental.json.impl.JreJsonFactory;
import elemental.json.impl.JsonUtil;

/**
 * Utilities related to {@link com.google.gwt.i18n.client.TimeZone}.
 *
 * @author Vaadin Ltd
 * @since 8.2
 */
public final class TimeZoneUtil implements Serializable {

    /**
     * The start year used to send the time zone transition dates.
     */
    private static final int STARTING_YEAR = 1980;

    /**
     * Till how many years from now, should we send the time zone transition
     * dates.
     */
    private static final int YEARS_FROM_NOW = 20;

    private TimeZoneUtil() {
        // Static utils only
    }

    /**
     * Returns a JSON string of the specified {@code zoneId} and {@link Locale},
     * which is used in
     * {@link com.google.gwt.i18n.client.TimeZone#createTimeZone(String)}.
     *
     * @param zoneId
     *            the {@link ZoneId} to get the daylight transitions from
     * @param locale
     *            the locale used to determine the short name of the time zone
     *
     * @return the encoded string
     */
    public static String toJSON(ZoneId zoneId, Locale locale) {
        if (zoneId == null || locale == null) {
            return null;
        }
        ZoneRules rules = zoneId.getRules();
        TimeZone timeZone = TimeZone.getTimeZone(zoneId);
        List<Long> transitionsList = new ArrayList<>();

        TimeZoneInfo info = new TimeZoneInfo();

        int endYear = LocalDate.now().getYear() + YEARS_FROM_NOW;
        if (timeZone.useDaylightTime()) {
            for (int year = STARTING_YEAR; year <= endYear; year++) {
                ZonedDateTime i = LocalDateTime.of(year, 1, 1, 0, 0)
                        .atZone(zoneId);
                while (true) {
                    ZoneOffsetTransition t = rules
                            .nextTransition(i.toInstant());
                    if (t == null) {
                        break;
                    }
                    i = t.getInstant().atZone(zoneId);
                    if (i.toLocalDate().getYear() != year) {
                        break;
                    }
                    long epochHours = Duration
                            .ofSeconds(t.getInstant().getEpochSecond())
                            .toHours();
                    long duration = Math.max(t.getDuration().toMinutes(), 0);
                    transitionsList.add(epochHours);
                    transitionsList.add(duration);
                }
            }
        }
        info.id = zoneId.getId();
        info.transitions = transitionsList.stream().mapToLong(l -> l).toArray();
        info.std_offset = (int) Duration.ofMillis(timeZone.getRawOffset())
                .toMinutes();
        info.names = new String[] {
                timeZone.getDisplayName(false, TimeZone.SHORT, locale),
                timeZone.getDisplayName(false, TimeZone.LONG, locale),
                timeZone.getDisplayName(true, TimeZone.SHORT, locale),
                timeZone.getDisplayName(true, TimeZone.LONG, locale) };

        return stringify(info);
    }

    private static String stringify(TimeZoneInfo info) {
        JreJsonFactory factory = new JreJsonFactory();
        JsonObject object = factory.createObject();
        object.put("id", info.id);
        object.put("std_offset", info.std_offset);
        object.put("names", getArray(factory, info.names));
        object.put("transitions", getArray(factory, info.transitions));
        return JsonUtil.stringify(object);
    }

    private static JsonArray getArray(JreJsonFactory factory, long[] array) {
        JsonArray jsonArray = factory.createArray();
        for (int i = 0; i < array.length; i++) {
            jsonArray.set(i, array[i]);
        }
        return jsonArray;
    }

    private static JsonArray getArray(JreJsonFactory factory, String[] array) {
        JsonArray jsonArray = factory.createArray();
        for (int i = 0; i < array.length; i++) {
            jsonArray.set(i, array[i]);
        }
        return jsonArray;
    }

    private static class TimeZoneInfo implements Serializable {
        String id;
        int std_offset;
        String[] names;
        long[] transitions;
    }
}