Debian Codegraph @

src/main/org/h2/util/TimeZoneProvider.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.util;
7
8 import java.time.Instant;
9 import java.time.LocalDateTime;
10 import java.time.ZoneId;
11 import java.time.ZoneOffset;
12 import java.time.ZonedDateTime;
13 import java.time.format.DateTimeFormatter;
14 import java.time.zone.ZoneRules;
15 import java.util.Locale;
16
17 /**
18 * Provides access to time zone API.
19 */
20 public abstract class TimeZoneProvider {
21
22 /**
23 * The UTC time zone provider.
24 */
25 public static final TimeZoneProvider UTC = new Simple((short) 0);
26
27 /**
28 * A small cache for timezone providers.
29 */
30 public static TimeZoneProvider[] CACHE;
31
32 /**
33 * The number of cache elements (needs to be a power of 2).
34 */
35 private static final int CACHE_SIZE = 32;
36
37 /**
38 * Returns the time zone provider with the specified offset.
39 *
40 * @param offset
41 * UTC offset in seconds
42 * @return the time zone provider with the specified offset
43 */
44 public static TimeZoneProvider ofOffset(int offset) {
45 if (offset == 0) {
46 return UTC;
47 }
48 if (offset < (-18 * 60 * 60) || offset > (18 * 60 * 60)) {
49 throw new IllegalArgumentException("Time zone offset " + offset + " seconds is out of range");
50 }
51 return new Simple(offset);
52 }
53
54 /**
55 * Returns the time zone provider with the specified name.
56 *
57 * @param id
58 * the ID of the time zone
59 * @return the time zone provider with the specified name
60 * @throws RuntimeException
61 * if time zone with specified ID isn't known
62 */
63 public static TimeZoneProvider ofId(String id) throws RuntimeException {
64 int length = id.length();
65 if (length == 1 && id.charAt(0) == 'Z') {
66 return UTC;
67 }
68 int index = 0;
69 if (id.startsWith("GMT") || id.startsWith("UTC")) {
70 if (length == 3) {
71 return UTC;
72 }
73 index = 3;
74 }
75 if (length > index) {
76 boolean negative = false;
77 char c = id.charAt(index);
78 if (length > index + 1) {
79 if (c == '+') {
80 c = id.charAt(++index);
81 } else if (c == '-') {
82 negative = true;
83 c = id.charAt(++index);
84 }
85 }
86 if (index != 3 && c >= '0' && c <= '9') {
87 int hour = c - '0';
88 if (++index < length) {
89 c = id.charAt(index);
90 if (c >= '0' && c <= '9') {
91 hour = hour * 10 + c - '0';
92 index++;
93 }
94 }
95 if (index == length) {
96 int offset = hour * 3_600;
97 return ofOffset(negative ? -offset : offset);
98 }
99 if (id.charAt(index) == ':') {
100 if (++index < length) {
101 c = id.charAt(index);
102 if (c >= '0' && c <= '9') {
103 int minute = c - '0';
104 if (++index < length) {
105 c = id.charAt(index);
106 if (c >= '0' && c <= '9') {
107 minute = minute * 10 + c - '0';
108 index++;
109 }
110 }
111 if (index == length) {
112 int offset = (hour * 60 + minute) * 60;
113 return ofOffset(negative ? -offset : offset);
114 }
115 if (id.charAt(index) == ':') {
116 if (++index < length) {
117 c = id.charAt(index);
118 if (c >= '0' && c <= '9') {
119 int second = c - '0';
120 if (++index < length) {
121 c = id.charAt(index);
122 if (c >= '0' && c <= '9') {
123 second = second * 10 + c - '0';
124 index++;
125 }
126 }
127 if (index == length) {
128 int offset = (hour * 60 + minute) * 60 + second;
129 return ofOffset(negative ? -offset : offset);
130 }
131 }
132 }
133 }
134 }
135 }
136 }
137 }
138 if (index > 0) {
139 throw new IllegalArgumentException(id);
140 }
141 }
142 int hash = id.hashCode() & (CACHE_SIZE - 1);
143 TimeZoneProvider[] cache = CACHE;
144 if (cache != null) {
145 TimeZoneProvider provider = cache[hash];
146 if (provider != null && provider.getId().equals(id)) {
147 return provider;
148 }
149 }
150 TimeZoneProvider provider = new WithTimeZone(ZoneId.of(id, ZoneId.SHORT_IDS));
151 if (cache == null) {
152 CACHE = cache = new TimeZoneProvider[CACHE_SIZE];
153 }
154 cache[hash] = provider;
155 return provider;
156 }
157
158 /**
159 * Returns the time zone provider for the system default time zone.
160 *
161 * @return the time zone provider for the system default time zone
162 */
163 public static TimeZoneProvider getDefault() {
164 ZoneId zoneId = ZoneId.systemDefault();
165 ZoneOffset offset;
166 if (zoneId instanceof ZoneOffset) {
167 offset = (ZoneOffset) zoneId;
168 } else {
169 ZoneRules rules = zoneId.getRules();
170 if (!rules.isFixedOffset()) {
171 return new WithTimeZone(zoneId);
172 }
173 offset = rules.getOffset(Instant.EPOCH);
174 }
175 return ofOffset(offset.getTotalSeconds());
176 }
177
178 /**
179 * Calculates the time zone offset in seconds for the specified EPOCH
180 * seconds.
181 *
182 * @param epochSeconds
183 * seconds since EPOCH
184 * @return time zone offset in minutes
185 */
186 public abstract int getTimeZoneOffsetUTC(long epochSeconds);
187
188 /**
189 * Calculates the time zone offset in seconds for the specified date value
190 * and nanoseconds since midnight in local time.
191 *
192 * @param dateValue
193 * date value
194 * @param timeNanos
195 * nanoseconds since midnight
196 * @return time zone offset in minutes
197 */
198 public abstract int getTimeZoneOffsetLocal(long dateValue, long timeNanos);
199
200 /**
201 * Calculates the epoch seconds from local date and time.
202 *
203 * @param dateValue
204 * date value
205 * @param timeNanos
206 * nanoseconds since midnight
207 * @return the epoch seconds value
208 */
209 public abstract long getEpochSecondsFromLocal(long dateValue, long timeNanos);
210
211 /**
212 * Returns the ID of the time zone.
213 *
214 * @return the ID of the time zone
215 */
216 public abstract String getId();
217
218 /**
219 * Get the standard time name or daylight saving time name of the time zone.
220 *
221 * @param epochSeconds
222 * seconds since EPOCH
223 * @return the standard time name or daylight saving time name of the time
224 * zone
225 */
226 public abstract String getShortId(long epochSeconds);
227
228 /**
229 * Returns whether this is a simple time zone provider with a fixed offset
230 * from UTC.
231 *
232 * @return whether this is a simple time zone provider with a fixed offset
233 * from UTC
234 */
235 public boolean hasFixedOffset() {
236 return false;
237 }
238
239 /**
240 * Time zone provider with offset.
241 */
242 private static final class Simple extends TimeZoneProvider {
243
244 private final int offset;
245
246 private volatile String id;
247
248 Simple(int offset) {
249 this.offset = offset;
250 }
251
252 @Override
253 public int hashCode() {
254 return offset + 129607;
255 }
256
257 @Override
258 public boolean equals(Object obj) {
259 if (this == obj) {
260 return true;
261 }
262 if (obj == null || obj.getClass() != Simple.class) {
263 return false;
264 }
265 return offset == ((Simple) obj).offset;
266 }
267
268 @Override
269 public int getTimeZoneOffsetUTC(long epochSeconds) {
270 return offset;
271 }
272
273 @Override
274 public int getTimeZoneOffsetLocal(long dateValue, long timeNanos) {
275 return offset;
276 }
277
278 @Override
279 public long getEpochSecondsFromLocal(long dateValue, long timeNanos) {
280 return DateTimeUtils.getEpochSeconds(dateValue, timeNanos, offset);
281 }
282
283 @Override
284 public String getId() {
285 String id = this.id;
286 if (id == null) {
287 this.id = id = DateTimeUtils.timeZoneNameFromOffsetSeconds(offset);
288 }
289 return id;
290 }
291
292 @Override
293 public String getShortId(long epochSeconds) {
294 return getId();
295 }
296
297 @Override
298 public boolean hasFixedOffset() {
299 return true;
300 }
301
302 @Override
303 public String toString() {
304 return "TimeZoneProvider " + getId();
305 }
306
307 }
308
309 /**
310 * Time zone provider with time zone.
311 */
312 static final class WithTimeZone extends TimeZoneProvider {
313
314 /**
315 * Number of seconds in 400 years.
316 */
317 static final long SECONDS_PER_PERIOD = 146_097L * 60 * 60 * 24;
318
319 /**
320 * Number of seconds per year.
321 */
322 static final long SECONDS_PER_YEAR = SECONDS_PER_PERIOD / 400;
323
324 private static volatile DateTimeFormatter TIME_ZONE_FORMATTER;
325
326 private final ZoneId zoneId;
327
328 WithTimeZone(ZoneId timeZone) {
329 this.zoneId = timeZone;
330 }
331
332 @Override
333 public int hashCode() {
334 return zoneId.hashCode() + 951689;
335 }
336
337 @Override
338 public boolean equals(Object obj) {
339 if (this == obj) {
340 return true;
341 }
342 if (obj == null || obj.getClass() != WithTimeZone.class) {
343 return false;
344 }
345 return zoneId.equals(((WithTimeZone) obj).zoneId);
346 }
347
348 @Override
349 public int getTimeZoneOffsetUTC(long epochSeconds) {
350 /*
351 * Construct an Instant with EPOCH seconds within the range
352 * -31,557,014,135,532,000..31,556,889,832,715,999
353 * (-999999999-01-01T00:00-18:00..
354 * +999999999-12-31T23:59:59.999999999+18:00). Too large and too
355 * small EPOCH seconds are replaced with EPOCH seconds within the
356 * range using the 400 years period of the Gregorian calendar.
357 *
358 * H2 has slightly wider range of EPOCH seconds than Instant, and
359 * ZoneRules.getOffset(Instant) does not support all Instant values
360 * in all time zones.
361 */
362 if (epochSeconds > 31_556_889_832_715_999L) {
363 epochSeconds -= SECONDS_PER_PERIOD;
364 } else if (epochSeconds < -31_557_014_135_532_000L) {
365 epochSeconds += SECONDS_PER_PERIOD;
366 }
367 return zoneId.getRules().getOffset(Instant.ofEpochSecond(epochSeconds)).getTotalSeconds();
368 }
369
370 @Override
371 public int getTimeZoneOffsetLocal(long dateValue, long timeNanos) {
372 int second = (int) (timeNanos / DateTimeUtils.NANOS_PER_SECOND);
373 int minute = second / 60;
374 second -= minute * 60;
375 int hour = minute / 60;
376 minute -= hour * 60;
377 return ZonedDateTime.of(LocalDateTime.of(yearForCalendar(DateTimeUtils.yearFromDateValue(dateValue)),
378 DateTimeUtils.monthFromDateValue(dateValue), DateTimeUtils.dayFromDateValue(dateValue), hour,
379 minute, second), zoneId).getOffset().getTotalSeconds();
380 }
381
382 @Override
383 public long getEpochSecondsFromLocal(long dateValue, long timeNanos) {
384 int second = (int) (timeNanos / DateTimeUtils.NANOS_PER_SECOND);
385 int minute = second / 60;
386 second -= minute * 60;
387 int hour = minute / 60;
388 minute -= hour * 60;
389 int year = DateTimeUtils.yearFromDateValue(dateValue);
390 int yearForCalendar = yearForCalendar(year);
391 long epoch = ZonedDateTime
392 .of(LocalDateTime.of(yearForCalendar, DateTimeUtils.monthFromDateValue(dateValue),
393 DateTimeUtils.dayFromDateValue(dateValue), hour, minute, second), zoneId)
394 .toOffsetDateTime().toEpochSecond();
395 return epoch + (year - yearForCalendar) * SECONDS_PER_YEAR;
396 }
397
398 @Override
399 public String getId() {
400 return zoneId.getId();
401 }
402
403 @Override
404 public String getShortId(long epochSeconds) {
405 DateTimeFormatter timeZoneFormatter = TIME_ZONE_FORMATTER;
406 if (timeZoneFormatter == null) {
407 TIME_ZONE_FORMATTER = timeZoneFormatter = DateTimeFormatter.ofPattern("z", Locale.ENGLISH);
408 }
409 return ZonedDateTime.ofInstant(Instant.ofEpochSecond(epochSeconds), zoneId).format(timeZoneFormatter);
410 }
411
412 /**
413 * Returns a year within the range -999,999,999..999,999,999 for the
414 * given year. Too large and too small years are replaced with years
415 * within the range using the 400 years period of the Gregorian
416 * calendar.
417 *
418 * Because we need them only to calculate a time zone offset, it's safe
419 * to normalize them to such range.
420 *
421 * @param year
422 * the year
423 * @return the specified year or the replacement year within the range
424 */
425 private static int yearForCalendar(int year) {
426 if (year > 999_999_999) {
427 year -= 400;
428 } else if (year < -999_999_999) {
429 year += 400;
430 }
431 return year;
432 }
433
434 @Override
435 public String toString() {
436 return "TimeZoneProvider " + zoneId.getId();
437 }
438
439 }
440
441 }