Debian Codegraph @

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

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, and the
3 * EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 * Iso8601: Initial Developer: Robert Rathsack (firstName dot lastName at gmx
6 * dot de)
7 */
8 package org.h2.util;
9
10 import java.time.Instant;
11
12 import org.h2.api.ErrorCode;
13 import org.h2.engine.CastDataProvider;
14 import org.h2.message.DbException;
15 import org.h2.value.TypeInfo;
16 import org.h2.value.Value;
17 import org.h2.value.ValueDate;
18 import org.h2.value.ValueTime;
19 import org.h2.value.ValueTimeTimeZone;
20 import org.h2.value.ValueTimestamp;
21 import org.h2.value.ValueTimestampTimeZone;
22
23 /**
24 * This utility class contains time conversion functions.
25 * <p>
26 * Date value: a bit field with bits for the year, month, and day. Absolute day:
27 * the day number (0 means 1970-01-01).
28 */
29 public class DateTimeUtils {
30
31 /**
32 * The number of milliseconds per day.
33 */
34 public static final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
35
36 /**
37 * The number of seconds per day.
38 */
39 public static final long SECONDS_PER_DAY = 24 * 60 * 60;
40
41 /**
42 * The number of nanoseconds per second.
43 */
44 public static final long NANOS_PER_SECOND = 1_000_000_000;
45
46 /**
47 * The number of nanoseconds per minute.
48 */
49 public static final long NANOS_PER_MINUTE = 60 * NANOS_PER_SECOND;
50
51 /**
52 * The number of nanoseconds per hour.
53 */
54 public static final long NANOS_PER_HOUR = 60 * NANOS_PER_MINUTE;
55
56 /**
57 * The number of nanoseconds per day.
58 */
59 public static final long NANOS_PER_DAY = MILLIS_PER_DAY * 1_000_000;
60
61 /**
62 * The offset of year bits in date values.
63 */
64 public static final int SHIFT_YEAR = 9;
65
66 /**
67 * The offset of month bits in date values.
68 */
69 public static final int SHIFT_MONTH = 5;
70
71 /**
72 * Date value for 1970-01-01.
73 */
74 public static final int EPOCH_DATE_VALUE = (1970 << SHIFT_YEAR) + (1 << SHIFT_MONTH) + 1;
75
76 /**
77 * Minimum possible date value.
78 */
79 public static final long MIN_DATE_VALUE = (-1_000_000_000L << SHIFT_YEAR) + (1 << SHIFT_MONTH) + 1;
80
81 /**
82 * Maximum possible date value.
83 */
84 public static final long MAX_DATE_VALUE = (1_000_000_000L << SHIFT_YEAR) + (12 << SHIFT_MONTH) + 31;
85
86 private static final int[] NORMAL_DAYS_PER_MONTH = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
87
88 /**
89 * Multipliers for {@link #convertScale(long, int, long)} and
90 * {@link #appendNanos(StringBuilder, int)}.
91 */
92 static final int[] FRACTIONAL_SECONDS_TABLE = { 1_000_000_000, 100_000_000,
93 10_000_000, 1_000_000, 100_000, 10_000, 1_000, 100, 10, 1 };
94
95 private static volatile TimeZoneProvider LOCAL;
96
97 private DateTimeUtils() {
98 // utility class
99 }
100
101 /**
102 * Reset the cached calendar for default timezone, for example after
103 * changing the default timezone.
104 */
105 public static void resetCalendar() {
106 LOCAL = null;
107 }
108
109 /**
110 * Get the time zone provider for the default time zone.
111 *
112 * @return the time zone provider for the default time zone
113 */
114 public static TimeZoneProvider getTimeZone() {
115 TimeZoneProvider local = LOCAL;
116 if (local == null) {
117 LOCAL = local = TimeZoneProvider.getDefault();
118 }
119 return local;
120 }
121
122 /**
123 * Returns current timestamp.
124 *
125 * @param timeZone
126 * the time zone
127 * @return current timestamp
128 */
129 public static ValueTimestampTimeZone currentTimestamp(TimeZoneProvider timeZone) {
130 return currentTimestamp(timeZone, Instant.now());
131 }
132
133 /**
134 * Returns current timestamp using the specified instant for its value.
135 *
136 * @param timeZone
137 * the time zone
138 * @param now
139 * timestamp source, must be greater than or equal to
140 * 1970-01-01T00:00:00Z
141 * @return current timestamp
142 */
143 public static ValueTimestampTimeZone currentTimestamp(TimeZoneProvider timeZone, Instant now) {
144 /*
145 * This code intentionally does not support properly dates before UNIX
146 * epoch because such support is not required for current dates.
147 */
148 long second = now.getEpochSecond();
149 int offset = timeZone.getTimeZoneOffsetUTC(second);
150 second += offset;
151 return ValueTimestampTimeZone.fromDateValueAndNanos(dateValueFromAbsoluteDay(second / SECONDS_PER_DAY),
152 second % SECONDS_PER_DAY * 1_000_000_000 + now.getNano(), offset);
153 }
154
155 /**
156 * Parse a date string. The format is: [+|-]year-month-day
157 * or [+|-]yyyyMMdd.
158 *
159 * @param s the string to parse
160 * @param start the parse index start
161 * @param end the parse index end
162 * @return the date value
163 * @throws IllegalArgumentException if there is a problem
164 */
165 public static long parseDateValue(String s, int start, int end) {
166 if (s.charAt(start) == '+') {
167 // +year
168 start++;
169 }
170 // start at position 1 to support "-year"
171 int yEnd = s.indexOf('-', start + 1);
172 int mStart, mEnd, dStart;
173 if (yEnd > 0) {
174 // Standard [+|-]year-month-day format
175 mStart = yEnd + 1;
176 mEnd = s.indexOf('-', mStart);
177 if (mEnd <= mStart) {
178 throw new IllegalArgumentException(s);
179 }
180 dStart = mEnd + 1;
181 } else {
182 // Additional [+|-]yyyyMMdd format for compatibility
183 mEnd = dStart = end - 2;
184 yEnd = mStart = mEnd - 2;
185 // Accept only 3 or more digits in year for now
186 if (yEnd < start + 3) {
187 throw new IllegalArgumentException(s);
188 }
189 }
190 int year = Integer.parseInt(s.substring(start, yEnd));
191 int month = StringUtils.parseUInt31(s, mStart, mEnd);
192 int day = StringUtils.parseUInt31(s, dStart, end);
193 if (!isValidDate(year, month, day)) {
194 throw new IllegalArgumentException(year + "-" + month + "-" + day);
195 }
196 return dateValue(year, month, day);
197 }
198
199 /**
200 * Parse a time string. The format is: hour:minute[:second[.nanos]],
201 * hhmm[ss[.nanos]], or hour.minute.second[.nanos].
202 *
203 * @param s the string to parse
204 * @param start the parse index start
205 * @param end the parse index end
206 * @return the time in nanoseconds
207 * @throws IllegalArgumentException if there is a problem
208 */
209 public static long parseTimeNanos(String s, int start, int end) {
210 int hour, minute, second, nanos;
211 int hEnd = s.indexOf(':', start);
212 int mStart, mEnd, sStart, sEnd;
213 if (hEnd > 0) {
214 mStart = hEnd + 1;
215 mEnd = s.indexOf(':', mStart);
216 if (mEnd >= mStart) {
217 // Standard hour:minute:second[.nanos] format
218 sStart = mEnd + 1;
219 sEnd = s.indexOf('.', sStart);
220 } else {
221 // Additional hour:minute format for compatibility
222 mEnd = end;
223 sStart = sEnd = -1;
224 }
225 } else {
226 int t = s.indexOf('.', start);
227 if (t < 0) {
228 // Additional hhmm[ss] format for compatibility
229 hEnd = mStart = start + 2;
230 mEnd = mStart + 2;
231 int len = end - start;
232 if (len == 6) {
233 sStart = mEnd;
234 sEnd = -1;
235 } else if (len == 4) {
236 sStart = sEnd = -1;
237 } else {
238 throw new IllegalArgumentException(s);
239 }
240 } else if (t >= start + 6) {
241 // Additional hhmmss.nanos format for compatibility
242 if (t - start != 6) {
243 throw new IllegalArgumentException(s);
244 }
245 hEnd = mStart = start + 2;
246 mEnd = sStart = mStart + 2;
247 sEnd = t;
248 } else {
249 // Additional hour.minute.second[.nanos] IBM DB2 time format
250 hEnd = t;
251 mStart = hEnd + 1;
252 mEnd = s.indexOf('.', mStart);
253 if (mEnd <= mStart) {
254 throw new IllegalArgumentException(s);
255 }
256 sStart = mEnd + 1;
257 sEnd = s.indexOf('.', sStart);
258 }
259 }
260 hour = StringUtils.parseUInt31(s, start, hEnd);
261 if (hour >= 24) {
262 throw new IllegalArgumentException(s);
263 }
264 minute = StringUtils.parseUInt31(s, mStart, mEnd);
265 if (sStart > 0) {
266 if (sEnd < 0) {
267 second = StringUtils.parseUInt31(s, sStart, end);
268 nanos = 0;
269 } else {
270 second = StringUtils.parseUInt31(s, sStart, sEnd);
271 nanos = parseNanos(s, sEnd + 1, end);
272 }
273 } else {
274 second = nanos = 0;
275 }
276 if (minute >= 60 || second >= 60) {
277 throw new IllegalArgumentException(s);
278 }
279 return ((((hour * 60L) + minute) * 60) + second) * NANOS_PER_SECOND + nanos;
280 }
281
282 /**
283 * Parse nanoseconds.
284 *
285 * @param s String to parse.
286 * @param start Begin position at the string to read.
287 * @param end End position at the string to read.
288 * @return Parsed nanoseconds.
289 */
290 static int parseNanos(String s, int start, int end) {
291 if (start >= end) {
292 throw new IllegalArgumentException(s);
293 }
294 int nanos = 0, mul = 100_000_000;
295 do {
296 char c = s.charAt(start);
297 if (c < '0' || c > '9') {
298 throw new IllegalArgumentException(s);
299 }
300 nanos += mul * (c - '0');
301 // mul can become 0, but continue loop anyway to ensure that all
302 // remaining digits are valid
303 mul /= 10;
304 } while (++start < end);
305 return nanos;
306 }
307
308 /**
309 * Parses timestamp value from the specified string.
310 *
311 * @param s
312 * string to parse
313 * @param provider
314 * the cast information provider, may be {@code null} for
315 * Standard-compliant literals
316 * @param withTimeZone
317 * if {@code true} return {@link ValueTimestampTimeZone} instead of
318 * {@link ValueTimestamp}
319 * @return parsed timestamp
320 */
321 public static Value parseTimestamp(String s, CastDataProvider provider, boolean withTimeZone) {
322 int dateEnd = s.indexOf(' ');
323 if (dateEnd < 0) {
324 // ISO 8601 compatibility
325 dateEnd = s.indexOf('T');
326 if (dateEnd < 0 && provider != null && provider.getMode().allowDB2TimestampFormat) {
327 // DB2 also allows dash between date and time
328 dateEnd = s.indexOf('-', s.indexOf('-', s.indexOf('-') + 1) + 1);
329 }
330 }
331 int timeStart;
332 if (dateEnd < 0) {
333 dateEnd = s.length();
334 timeStart = -1;
335 } else {
336 timeStart = dateEnd + 1;
337 }
338 long dateValue = parseDateValue(s, 0, dateEnd);
339 long nanos;
340 TimeZoneProvider tz = null;
341 if (timeStart < 0) {
342 nanos = 0;
343 } else {
344 dateEnd++;
345 int timeEnd;
346 if (s.endsWith("Z")) {
347 tz = TimeZoneProvider.UTC;
348 timeEnd = s.length() - 1;
349 } else {
350 int timeZoneStart = s.indexOf('+', dateEnd);
351 if (timeZoneStart < 0) {
352 timeZoneStart = s.indexOf('-', dateEnd);
353 }
354 if (timeZoneStart >= 0) {
355 // Allow [timeZoneName] part after time zone offset
356 int offsetEnd = s.indexOf('[', timeZoneStart + 1);
357 if (offsetEnd < 0) {
358 offsetEnd = s.length();
359 }
360 tz = TimeZoneProvider.ofId(s.substring(timeZoneStart, offsetEnd));
361 if (s.charAt(timeZoneStart - 1) == ' ') {
362 timeZoneStart--;
363 }
364 timeEnd = timeZoneStart;
365 } else {
366 timeZoneStart = s.indexOf(' ', dateEnd);
367 if (timeZoneStart > 0) {
368 tz = TimeZoneProvider.ofId(s.substring(timeZoneStart + 1));
369 timeEnd = timeZoneStart;
370 } else {
371 timeEnd = s.length();
372 }
373 }
374 }
375 nanos = parseTimeNanos(s, dateEnd, timeEnd);
376 }
377 if (withTimeZone) {
378 int tzSeconds;
379 if (tz == null) {
380 tz = provider != null ? provider.currentTimeZone() : DateTimeUtils.getTimeZone();
381 }
382 if (tz != TimeZoneProvider.UTC) {
383 tzSeconds = tz.getTimeZoneOffsetUTC(tz.getEpochSecondsFromLocal(dateValue, nanos));
384 } else {
385 tzSeconds = 0;
386 }
387 return ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, nanos, tzSeconds);
388 } else if (tz != null) {
389 long seconds = tz.getEpochSecondsFromLocal(dateValue, nanos);
390 seconds += (provider != null ? provider.currentTimeZone() : DateTimeUtils.getTimeZone())
391 .getTimeZoneOffsetUTC(seconds);
392 dateValue = dateValueFromLocalSeconds(seconds);
393 nanos = nanos % 1_000_000_000 + nanosFromLocalSeconds(seconds);
394 }
395 return ValueTimestamp.fromDateValueAndNanos(dateValue, nanos);
396 }
397
398 /**
399 * Parses time value from the specified string.
400 *
401 * @param s
402 * string to parse
403 * @param provider
404 * the cast information provider, or {@code null}
405 * @param withTimeZone
406 * if {@code true} return {@link ValueTimeTimeZone} instead of
407 * {@link ValueTime}
408 * @return parsed time
409 */
410 public static Value parseTime(String s, CastDataProvider provider, boolean withTimeZone) {
411 int timeEnd;
412 TimeZoneProvider tz = null;
413 if (s.endsWith("Z")) {
414 tz = TimeZoneProvider.UTC;
415 timeEnd = s.length() - 1;
416 } else {
417 int timeZoneStart = s.indexOf('+', 1);
418 if (timeZoneStart < 0) {
419 timeZoneStart = s.indexOf('-', 1);
420 }
421 if (timeZoneStart >= 0) {
422 tz = TimeZoneProvider.ofId(s.substring(timeZoneStart));
423 if (s.charAt(timeZoneStart - 1) == ' ') {
424 timeZoneStart--;
425 }
426 timeEnd = timeZoneStart;
427 } else {
428 timeZoneStart = s.indexOf(' ', 1);
429 if (timeZoneStart > 0) {
430 tz = TimeZoneProvider.ofId(s.substring(timeZoneStart + 1));
431 timeEnd = timeZoneStart;
432 } else {
433 timeEnd = s.length();
434 }
435 }
436 if (tz != null && !tz.hasFixedOffset()) {
437 throw DbException.get(ErrorCode.INVALID_DATETIME_CONSTANT_2, "TIME WITH TIME ZONE", s);
438 }
439 }
440 long nanos = parseTimeNanos(s, 0, timeEnd);
441 if (withTimeZone) {
442 return ValueTimeTimeZone.fromNanos(nanos,
443 tz != null ? tz.getTimeZoneOffsetUTC(0L)
444 : (provider != null ? provider.currentTimestamp() : currentTimestamp(getTimeZone()))
445 .getTimeZoneOffsetSeconds());
446 }
447 if (tz != null) {
448 nanos = normalizeNanosOfDay(
449 nanos + ((provider != null ? provider.currentTimestamp() : currentTimestamp(getTimeZone()))
450 .getTimeZoneOffsetSeconds() - tz.getTimeZoneOffsetUTC(0L)) * NANOS_PER_SECOND);
451 }
452 return ValueTime.fromNanos(nanos);
453 }
454
455 /**
456 * Calculates the seconds since epoch for the specified date value,
457 * nanoseconds since midnight, and time zone offset.
458 * @param dateValue
459 * date value
460 * @param timeNanos
461 * nanoseconds since midnight
462 * @param offsetSeconds
463 * time zone offset in seconds
464 * @return seconds since epoch in UTC
465 */
466 public static long getEpochSeconds(long dateValue, long timeNanos, int offsetSeconds) {
467 return absoluteDayFromDateValue(dateValue) * SECONDS_PER_DAY + timeNanos / NANOS_PER_SECOND - offsetSeconds;
468 }
469
470 /**
471 * Extracts date value and nanos of day from the specified value.
472 *
473 * @param value
474 * value to extract fields from
475 * @param provider
476 * the cast information provider
477 * @return array with date value and nanos of day
478 */
479 public static long[] dateAndTimeFromValue(Value value, CastDataProvider provider) {
480 long dateValue = EPOCH_DATE_VALUE;
481 long timeNanos = 0;
482 if (value instanceof ValueTimestamp) {
483 ValueTimestamp v = (ValueTimestamp) value;
484 dateValue = v.getDateValue();
485 timeNanos = v.getTimeNanos();
486 } else if (value instanceof ValueDate) {
487 dateValue = ((ValueDate) value).getDateValue();
488 } else if (value instanceof ValueTime) {
489 timeNanos = ((ValueTime) value).getNanos();
490 } else if (value instanceof ValueTimestampTimeZone) {
491 ValueTimestampTimeZone v = (ValueTimestampTimeZone) value;
492 dateValue = v.getDateValue();
493 timeNanos = v.getTimeNanos();
494 } else if (value instanceof ValueTimeTimeZone) {
495 timeNanos = ((ValueTimeTimeZone) value).getNanos();
496 } else {
497 ValueTimestamp v = (ValueTimestamp) value.convertTo(TypeInfo.TYPE_TIMESTAMP, provider);
498 dateValue = v.getDateValue();
499 timeNanos = v.getTimeNanos();
500 }
501 return new long[] {dateValue, timeNanos};
502 }
503
504 /**
505 * Creates a new date-time value with the same type as original value. If
506 * original value is a ValueTimestampTimeZone or ValueTimeTimeZone, returned
507 * value will have the same time zone offset as original value.
508 *
509 * @param original
510 * original value
511 * @param dateValue
512 * date value for the returned value
513 * @param timeNanos
514 * nanos of day for the returned value
515 * @return new value with specified date value and nanos of day
516 */
517 public static Value dateTimeToValue(Value original, long dateValue, long timeNanos) {
518 switch (original.getValueType()) {
519 case Value.DATE:
520 return ValueDate.fromDateValue(dateValue);
521 case Value.TIME:
522 return ValueTime.fromNanos(timeNanos);
523 case Value.TIME_TZ:
524 return ValueTimeTimeZone.fromNanos(timeNanos, ((ValueTimeTimeZone) original).getTimeZoneOffsetSeconds());
525 case Value.TIMESTAMP:
526 default:
527 return ValueTimestamp.fromDateValueAndNanos(dateValue, timeNanos);
528 case Value.TIMESTAMP_TZ:
529 return ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, timeNanos,
530 ((ValueTimestampTimeZone) original).getTimeZoneOffsetSeconds());
531 }
532 }
533
534 /**
535 * Returns day of week.
536 *
537 * @param dateValue
538 * the date value
539 * @param firstDayOfWeek
540 * first day of week, Monday as 1, Sunday as 7 or 0
541 * @return day of week
542 * @see #getIsoDayOfWeek(long)
543 */
544 public static int getDayOfWeek(long dateValue, int firstDayOfWeek) {
545 return getDayOfWeekFromAbsolute(absoluteDayFromDateValue(dateValue), firstDayOfWeek);
546 }
547
548 /**
549 * Get the day of the week from the absolute day value.
550 *
551 * @param absoluteValue the absolute day
552 * @param firstDayOfWeek the first day of the week
553 * @return the day of week
554 */
555 public static int getDayOfWeekFromAbsolute(long absoluteValue, int firstDayOfWeek) {
556 return absoluteValue >= 0 ? (int) ((absoluteValue - firstDayOfWeek + 11) % 7) + 1
557 : (int) ((absoluteValue - firstDayOfWeek - 2) % 7) + 7;
558 }
559
560 /**
561 * Returns number of day in year.
562 *
563 * @param dateValue
564 * the date value
565 * @return number of day in year
566 */
567 public static int getDayOfYear(long dateValue) {
568 int m = monthFromDateValue(dateValue);
569 int a = (367 * m - 362) / 12 + dayFromDateValue(dateValue);
570 if (m > 2) {
571 a--;
572 long y = yearFromDateValue(dateValue);
573 if ((y & 3) != 0 || (y % 100 == 0 && y % 400 != 0)) {
574 a--;
575 }
576 }
577 return a;
578 }
579
580 /**
581 * Returns ISO day of week.
582 *
583 * @param dateValue
584 * the date value
585 * @return ISO day of week, Monday as 1 to Sunday as 7
586 * @see #getSundayDayOfWeek(long)
587 */
588 public static int getIsoDayOfWeek(long dateValue) {
589 return getDayOfWeek(dateValue, 1);
590 }
591
592 /**
593 * Returns ISO number of week in year.
594 *
595 * @param dateValue
596 * the date value
597 * @return number of week in year
598 * @see #getIsoWeekYear(long)
599 * @see #getWeekOfYear(long, int, int)
600 */
601 public static int getIsoWeekOfYear(long dateValue) {
602 return getWeekOfYear(dateValue, 1, 4);
603 }
604
605 /**
606 * Returns ISO week year.
607 *
608 * @param dateValue
609 * the date value
610 * @return ISO week year
611 * @see #getIsoWeekOfYear(long)
612 * @see #getWeekYear(long, int, int)
613 */
614 public static int getIsoWeekYear(long dateValue) {
615 return getWeekYear(dateValue, 1, 4);
616 }
617
618 /**
619 * Returns day of week with Sunday as 1.
620 *
621 * @param dateValue
622 * the date value
623 * @return day of week, Sunday as 1 to Monday as 7
624 * @see #getIsoDayOfWeek(long)
625 */
626 public static int getSundayDayOfWeek(long dateValue) {
627 return getDayOfWeek(dateValue, 0);
628 }
629
630 /**
631 * Returns number of week in year.
632 *
633 * @param dateValue
634 * the date value
635 * @param firstDayOfWeek
636 * first day of week, Monday as 1, Sunday as 7 or 0
637 * @param minimalDaysInFirstWeek
638 * minimal days in first week of year
639 * @return number of week in year
640 * @see #getIsoWeekOfYear(long)
641 */
642 public static int getWeekOfYear(long dateValue, int firstDayOfWeek, int minimalDaysInFirstWeek) {
643 long abs = absoluteDayFromDateValue(dateValue);
644 int year = yearFromDateValue(dateValue);
645 long base = getWeekYearAbsoluteStart(year, firstDayOfWeek, minimalDaysInFirstWeek);
646 if (abs - base < 0) {
647 base = getWeekYearAbsoluteStart(year - 1, firstDayOfWeek, minimalDaysInFirstWeek);
648 } else if (monthFromDateValue(dateValue) == 12 && 24 + minimalDaysInFirstWeek < dayFromDateValue(dateValue)) {
649 if (abs >= getWeekYearAbsoluteStart(year + 1, firstDayOfWeek, minimalDaysInFirstWeek)) {
650 return 1;
651 }
652 }
653 return (int) ((abs - base) / 7) + 1;
654 }
655
656 /**
657 * Get absolute day of the first day in the week year.
658 *
659 * @param weekYear
660 * the week year
661 * @param firstDayOfWeek
662 * first day of week, Monday as 1, Sunday as 7 or 0
663 * @param minimalDaysInFirstWeek
664 * minimal days in first week of year
665 * @return absolute day of the first day in the week year
666 */
667 public static long getWeekYearAbsoluteStart(int weekYear, int firstDayOfWeek, int minimalDaysInFirstWeek) {
668 long first = absoluteDayFromYear(weekYear);
669 int daysInFirstWeek = 8 - getDayOfWeekFromAbsolute(first, firstDayOfWeek);
670 long base = first + daysInFirstWeek;
671 if (daysInFirstWeek >= minimalDaysInFirstWeek) {
672 base -= 7;
673 }
674 return base;
675 }
676
677 /**
678 * Returns week year.
679 *
680 * @param dateValue
681 * the date value
682 * @param firstDayOfWeek
683 * first day of week, Monday as 1, Sunday as 7 or 0
684 * @param minimalDaysInFirstWeek
685 * minimal days in first week of year
686 * @return week year
687 * @see #getIsoWeekYear(long)
688 */
689 public static int getWeekYear(long dateValue, int firstDayOfWeek, int minimalDaysInFirstWeek) {
690 long abs = absoluteDayFromDateValue(dateValue);
691 int year = yearFromDateValue(dateValue);
692 long base = getWeekYearAbsoluteStart(year, firstDayOfWeek, minimalDaysInFirstWeek);
693 if (abs < base) {
694 return year - 1;
695 } else if (monthFromDateValue(dateValue) == 12 && 24 + minimalDaysInFirstWeek < dayFromDateValue(dateValue)) {
696 if (abs >= getWeekYearAbsoluteStart(year + 1, firstDayOfWeek, minimalDaysInFirstWeek)) {
697 return year + 1;
698 }
699 }
700 return year;
701 }
702
703 /**
704 * Returns number of days in month.
705 *
706 * @param year the year
707 * @param month the month
708 * @return number of days in the specified month
709 */
710 public static int getDaysInMonth(int year, int month) {
711 if (month != 2) {
712 return NORMAL_DAYS_PER_MONTH[month];
713 }
714 return isLeapYear(year) ? 29 : 28;
715 }
716
717 static boolean isLeapYear(int year) {
718 return (year & 3) == 0 && (year % 100 != 0 || year % 400 == 0);
719 }
720
721 /**
722 * Verify if the specified date is valid.
723 *
724 * @param year the year
725 * @param month the month (January is 1)
726 * @param day the day (1 is the first of the month)
727 * @return true if it is valid
728 */
729 public static boolean isValidDate(int year, int month, int day) {
730 return month >= 1 && month <= 12 && day >= 1 && day <= getDaysInMonth(year, month);
731 }
732
733 /**
734 * Get the year from a date value.
735 *
736 * @param x the date value
737 * @return the year
738 */
739 public static int yearFromDateValue(long x) {
740 return (int) (x >>> SHIFT_YEAR);
741 }
742
743 /**
744 * Get the month from a date value.
745 *
746 * @param x the date value
747 * @return the month (1..12)
748 */
749 public static int monthFromDateValue(long x) {
750 return (int) (x >>> SHIFT_MONTH) & 15;
751 }
752
753 /**
754 * Get the day of month from a date value.
755 *
756 * @param x the date value
757 * @return the day (1..31)
758 */
759 public static int dayFromDateValue(long x) {
760 return (int) (x & 31);
761 }
762
763 /**
764 * Get the date value from a given date.
765 *
766 * @param year the year
767 * @param month the month (1..12)
768 * @param day the day (1..31)
769 * @return the date value
770 */
771 public static long dateValue(long year, int month, int day) {
772 return (year << SHIFT_YEAR) | (month << SHIFT_MONTH) | day;
773 }
774
775 /**
776 * Get the date value from a given denormalized date with possible out of range
777 * values of month and/or day. Used after addition or subtraction month or years
778 * to (from) it to get a valid date.
779 *
780 * @param year
781 * the year
782 * @param month
783 * the month, if out of range month and year will be normalized
784 * @param day
785 * the day of the month, if out of range it will be saturated
786 * @return the date value
787 */
788 public static long dateValueFromDenormalizedDate(long year, long month, int day) {
789 long mm1 = month - 1;
790 long yd = mm1 / 12;
791 if (mm1 < 0 && yd * 12 != mm1) {
792 yd--;
793 }
794 int y = (int) (year + yd);
795 int m = (int) (month - yd * 12);
796 if (day < 1) {
797 day = 1;
798 } else {
799 int max = getDaysInMonth(y, m);
800 if (day > max) {
801 day = max;
802 }
803 }
804 return dateValue(y, m, day);
805 }
806
807 /**
808 * Convert a local seconds to an encoded date.
809 *
810 * @param localSeconds the seconds since 1970-01-01
811 * @return the date value
812 */
813 public static long dateValueFromLocalSeconds(long localSeconds) {
814 long absoluteDay = localSeconds / SECONDS_PER_DAY;
815 // Round toward negative infinity
816 if (localSeconds < 0 && (absoluteDay * SECONDS_PER_DAY != localSeconds)) {
817 absoluteDay--;
818 }
819 return dateValueFromAbsoluteDay(absoluteDay);
820 }
821
822 /**
823 * Convert a time in seconds in local time to the nanoseconds since midnight.
824 *
825 * @param localSeconds the seconds since 1970-01-01
826 * @return the nanoseconds
827 */
828 public static long nanosFromLocalSeconds(long localSeconds) {
829 localSeconds %= SECONDS_PER_DAY;
830 if (localSeconds < 0) {
831 localSeconds += SECONDS_PER_DAY;
832 }
833 return localSeconds * NANOS_PER_SECOND;
834 }
835
836 /**
837 * Calculate the normalized nanos of day.
838 *
839 * @param nanos the nanoseconds (may be negative or larger than one day)
840 * @return the nanos of day within a day
841 */
842 public static long normalizeNanosOfDay(long nanos) {
843 nanos %= NANOS_PER_DAY;
844 if (nanos < 0) {
845 nanos += NANOS_PER_DAY;
846 }
847 return nanos;
848 }
849
850 /**
851 * Calculate the absolute day for a January, 1 of the specified year.
852 *
853 * @param year
854 * the year
855 * @return the absolute day
856 */
857 public static long absoluteDayFromYear(long year) {
858 long a = 365 * year - 719_528;
859 if (year >= 0) {
860 a += (year + 3) / 4 - (year + 99) / 100 + (year + 399) / 400;
861 } else {
862 a -= year / -4 - year / -100 + year / -400;
863 }
864 return a;
865 }
866
867 /**
868 * Calculate the absolute day from an encoded date value.
869 *
870 * @param dateValue the date value
871 * @return the absolute day
872 */
873 public static long absoluteDayFromDateValue(long dateValue) {
874 return absoluteDay(yearFromDateValue(dateValue), monthFromDateValue(dateValue), dayFromDateValue(dateValue));
875 }
876
877 /**
878 * Calculate the absolute day.
879 *
880 * @param y year
881 * @param m month
882 * @param d day
883 * @return the absolute day
884 */
885 static long absoluteDay(long y, int m, int d) {
886 long a = absoluteDayFromYear(y) + (367 * m - 362) / 12 + d - 1;
887 if (m > 2) {
888 a--;
889 if ((y & 3) != 0 || (y % 100 == 0 && y % 400 != 0)) {
890 a--;
891 }
892 }
893 return a;
894 }
895
896 /**
897 * Calculate the encoded date value from an absolute day.
898 *
899 * @param absoluteDay the absolute day
900 * @return the date value
901 */
902 public static long dateValueFromAbsoluteDay(long absoluteDay) {
903 long d = absoluteDay + 719_468;
904 long a = 0;
905 if (d < 0) {
906 a = (d + 1) / 146_097 - 1;
907 d -= a * 146_097;
908 a *= 400;
909 }
910 long y = (400 * d + 591) / 146_097;
911 int day = (int) (d - (365 * y + y / 4 - y / 100 + y / 400));
912 if (day < 0) {
913 y--;
914 day = (int) (d - (365 * y + y / 4 - y / 100 + y / 400));
915 }
916 y += a;
917 int m = (day * 5 + 2) / 153;
918 day -= (m * 306 + 5) / 10 - 1;
919 if (m >= 10) {
920 y++;
921 m -= 12;
922 }
923 return dateValue(y, m + 3, day);
924 }
925
926 /**
927 * Return the next date value.
928 *
929 * @param dateValue
930 * the date value
931 * @return the next date value
932 */
933 public static long incrementDateValue(long dateValue) {
934 int day = dayFromDateValue(dateValue);
935 if (day < 28) {
936 return dateValue + 1;
937 }
938 int year = yearFromDateValue(dateValue);
939 int month = monthFromDateValue(dateValue);
940 if (day < getDaysInMonth(year, month)) {
941 return dateValue + 1;
942 }
943 if (month < 12) {
944 month++;
945 } else {
946 month = 1;
947 year++;
948 }
949 return dateValue(year, month, 1);
950 }
951
952 /**
953 * Return the previous date value.
954 *
955 * @param dateValue
956 * the date value
957 * @return the previous date value
958 */
959 public static long decrementDateValue(long dateValue) {
960 if (dayFromDateValue(dateValue) > 1) {
961 return dateValue - 1;
962 }
963 int year = yearFromDateValue(dateValue);
964 int month = monthFromDateValue(dateValue);
965 if (month > 1) {
966 month--;
967 } else {
968 month = 12;
969 year--;
970 }
971 return dateValue(year, month, getDaysInMonth(year, month));
972 }
973
974 /**
975 * Append a date to the string builder.
976 *
977 * @param builder the target string builder
978 * @param dateValue the date value
979 * @return the specified string builder
980 */
981 public static StringBuilder appendDate(StringBuilder builder, long dateValue) {
982 int y = yearFromDateValue(dateValue);
983 if (y < 1_000 && y > -1_000) {
984 if (y < 0) {
985 builder.append('-');
986 y = -y;
987 }
988 StringUtils.appendZeroPadded(builder, 4, y);
989 } else {
990 builder.append(y);
991 }
992 StringUtils.appendTwoDigits(builder.append('-'), monthFromDateValue(dateValue)).append('-');
993 return StringUtils.appendTwoDigits(builder, dayFromDateValue(dateValue));
994 }
995
996 /**
997 * Append a time to the string builder.
998 *
999 * @param builder the target string builder
1000 * @param nanos the time in nanoseconds
1001 * @return the specified string builder
1002 */
1003 public static StringBuilder appendTime(StringBuilder builder, long nanos) {
1004 if (nanos < 0) {
1005 builder.append('-');
1006 nanos = -nanos;
1007 }
1008 /*
1009 * nanos now either in range from 0 to Long.MAX_VALUE or equals to
1010 * Long.MIN_VALUE. We need to divide nanos by 1,000,000,000 with
1011 * unsigned division to get correct result. The simplest way to do this
1012 * with such constraints is to divide -nanos by -1,000,000,000.
1013 */
1014 long s = -nanos / -1_000_000_000;
1015 nanos -= s * 1_000_000_000;
1016 int m = (int) (s / 60);
1017 s -= m * 60;
1018 int h = m / 60;
1019 m -= h * 60;
1020 StringUtils.appendTwoDigits(builder, h).append(':');
1021 StringUtils.appendTwoDigits(builder, m).append(':');
1022 StringUtils.appendTwoDigits(builder, (int) s);
1023 return appendNanos(builder, (int) nanos);
1024 }
1025
1026 /**
1027 * Append nanoseconds of time, if any.
1028 *
1029 * @param builder string builder to append to
1030 * @param nanos nanoseconds of second
1031 * @return the specified string builder
1032 */
1033 static StringBuilder appendNanos(StringBuilder builder, int nanos) {
1034 if (nanos > 0) {
1035 builder.append('.');
1036 for (int i = 1; nanos < FRACTIONAL_SECONDS_TABLE[i]; i++) {
1037 builder.append('0');
1038 }
1039 if (nanos % 1_000 == 0) {
1040 nanos /= 1_000;
1041 if (nanos % 1_000 == 0) {
1042 nanos /= 1_000;
1043 }
1044 }
1045 if (nanos % 10 == 0) {
1046 nanos /= 10;
1047 if (nanos % 10 == 0) {
1048 nanos /= 10;
1049 }
1050 }
1051 builder.append(nanos);
1052 }
1053 return builder;
1054 }
1055
1056 /**
1057 * Append a time zone to the string builder.
1058 *
1059 * @param builder the target string builder
1060 * @param tz the time zone offset in seconds
1061 * @return the specified string builder
1062 */
1063 public static StringBuilder appendTimeZone(StringBuilder builder, int tz) {
1064 if (tz < 0) {
1065 builder.append('-');
1066 tz = -tz;
1067 } else {
1068 builder.append('+');
1069 }
1070 int rem = tz / 3_600;
1071 StringUtils.appendTwoDigits(builder, rem);
1072 tz -= rem * 3_600;
1073 if (tz != 0) {
1074 rem = tz / 60;
1075 StringUtils.appendTwoDigits(builder.append(':'), rem);
1076 tz -= rem * 60;
1077 if (tz != 0) {
1078 StringUtils.appendTwoDigits(builder.append(':'), tz);
1079 }
1080 }
1081 return builder;
1082 }
1083
1084 /**
1085 * Generates time zone name for the specified offset in seconds.
1086 *
1087 * @param offsetSeconds
1088 * time zone offset in seconds
1089 * @return time zone name
1090 */
1091 public static String timeZoneNameFromOffsetSeconds(int offsetSeconds) {
1092 if (offsetSeconds == 0) {
1093 return "UTC";
1094 }
1095 StringBuilder b = new StringBuilder(12);
1096 b.append("GMT");
1097 if (offsetSeconds < 0) {
1098 b.append('-');
1099 offsetSeconds = -offsetSeconds;
1100 } else {
1101 b.append('+');
1102 }
1103 StringUtils.appendTwoDigits(b, offsetSeconds / 3_600).append(':');
1104 offsetSeconds %= 3_600;
1105 StringUtils.appendTwoDigits(b, offsetSeconds / 60);
1106 offsetSeconds %= 60;
1107 if (offsetSeconds != 0) {
1108 b.append(':');
1109 StringUtils.appendTwoDigits(b, offsetSeconds);
1110 }
1111 return b.toString();
1112 }
1113
1114
1115 /**
1116 * Converts scale of nanoseconds.
1117 *
1118 * @param nanosOfDay nanoseconds of day
1119 * @param scale fractional seconds precision
1120 * @param range the allowed range of values (0..range-1)
1121 * @return scaled value
1122 */
1123 public static long convertScale(long nanosOfDay, int scale, long range) {
1124 if (scale >= 9) {
1125 return nanosOfDay;
1126 }
1127 int m = FRACTIONAL_SECONDS_TABLE[scale];
1128 long mod = nanosOfDay % m;
1129 if (mod >= m >>> 1) {
1130 nanosOfDay += m;
1131 }
1132 long r = nanosOfDay - mod;
1133 if (r >= range) {
1134 r = range - m;
1135 }
1136 return r;
1137 }
1138
1139 /**
1140 * Moves timestamp with time zone to a new time zone.
1141 *
1142 * @param dateValue the date value
1143 * @param timeNanos the nanoseconds since midnight
1144 * @param oldOffset old offset
1145 * @param newOffset new offset
1146 * @return timestamp with time zone with new offset
1147 */
1148 public static ValueTimestampTimeZone timestampTimeZoneAtOffset(long dateValue, long timeNanos, int oldOffset,
1149 int newOffset) {
1150 timeNanos += (newOffset - oldOffset) * DateTimeUtils.NANOS_PER_SECOND;
1151 // Value can be 18+18 hours before or after the limit
1152 if (timeNanos < 0) {
1153 timeNanos += DateTimeUtils.NANOS_PER_DAY;
1154 dateValue = DateTimeUtils.decrementDateValue(dateValue);
1155 if (timeNanos < 0) {
1156 timeNanos += DateTimeUtils.NANOS_PER_DAY;
1157 dateValue = DateTimeUtils.decrementDateValue(dateValue);
1158 }
1159 } else if (timeNanos >= DateTimeUtils.NANOS_PER_DAY) {
1160 timeNanos -= DateTimeUtils.NANOS_PER_DAY;
1161 dateValue = DateTimeUtils.incrementDateValue(dateValue);
1162 if (timeNanos >= DateTimeUtils.NANOS_PER_DAY) {
1163 timeNanos -= DateTimeUtils.NANOS_PER_DAY;
1164 dateValue = DateTimeUtils.incrementDateValue(dateValue);
1165 }
1166 }
1167 return ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, timeNanos, newOffset);
1168 }
1169
1170 }