Debian Codegraph @

net/sf/saxon/value/DateTimeValue.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.value;
9
10 import net.sf.saxon.Controller;
11 import net.sf.saxon.expr.XPathContext;
12 import net.sf.saxon.functions.AccessorFn;
13 import net.sf.saxon.lib.ConversionRules;
14 import net.sf.saxon.om.SequenceTool;
15 import net.sf.saxon.trans.Err;
16 import net.sf.saxon.trans.NoDynamicContextException;
17 import net.sf.saxon.trans.XPathException;
18 import net.sf.saxon.tree.util.FastStringBuffer;
19 import net.sf.saxon.type.AtomicType;
20 import net.sf.saxon.type.BuiltInAtomicType;
21 import net.sf.saxon.type.ConversionResult;
22 import net.sf.saxon.type.ValidationFailure;
23
24 import java.math.BigDecimal;
25 import java.math.BigInteger;
26 import java.math.RoundingMode;
27 import java.time.*;
28 import java.time.format.DateTimeParseException;
29 import java.time.temporal.ChronoField;
30 import java.time.temporal.TemporalAccessor;
31 import java.time.temporal.TemporalField;
32 import java.time.temporal.UnsupportedTemporalTypeException;
33 import java.util.*;
34
35 /**
36 * A value of type {@code xs:dateTime}. This contains integer fields year, month, day, hour, minute,
37 * second, and nanosecond. All these fields except year must be non-negative. In the internal
38 * representation, the sequence of years runs -2, -1, 0, +1, +2: that is, the year before year 1
39 * is year 0.
40 * <p>The value also contains a boolean flag <code>hasNoYearZero</code>. When this flag is set, accessor
41 * methods that expose the year value subtract one if it is non-positive: that is, year 0 is displayed
42 * as -1, year -1 as -2, and so on. Constructor methods, unless otherwise specified, do not set this
43 * flag.</p>
44 * <p>From Saxon 9.9, this class implements the Java 8 interface {@link TemporalAccessor} which enables
45 * it to interoperate with Java 8 temporal classes such as {@link Instant} and {@link ZonedDateTime}.</p>
46 */
47
48 public final class DateTimeValue extends CalendarValue
49 implements Comparable, TemporalAccessor {
50
51 private int year; // the year as written, +1 for BC years
52 private byte month; // the month as written, range 1-12
53 private byte day; // the day as written, range 1-31
54 private byte hour; // the hour as written (except for midnight), range 0-23
55 private byte minute; // the minutes as written, range 0-59
56 private byte second; // the seconds as written, range 0-59 (no leap seconds)
57 private int nanosecond; // the number of nanoseconds within the current second
58 private boolean hasNoYearZero; // true if XSD 1.0 rules apply for negative years
59
60 /**
61 * Private default constructor
62 */
63
64 private DateTimeValue() {
65 }
66
67 /**
68 * Get the dateTime value representing the nominal
69 * date/time of this transformation run. Two calls within the same
70 * query or transformation will always return the same answer.
71 *
72 * @param context the XPath dynamic context. May be null, in which case
73 * the current date and time are taken directly from the system clock
74 * @return the current xs:dateTime
75 */
76
77 /*@Nullable*/
78 public static DateTimeValue getCurrentDateTime(/*@Nullable*/ XPathContext context) {
79 Controller c;
80 if (context == null || (c = context.getController()) == null) {
81 // non-XSLT/XQuery environment
82 // We also take this path when evaluating compile-time expressions that require an implicit timezone.
83 return now();
84 } else {
85 return c.getCurrentDateTime();
86 }
87 }
88
89 /**
90 * Get the dateTime value representing the moment of invocation of this method,
91 * in the default timezone set for the platform on which the application is running.
92 * @return the current dateTime, in the local timezone for the platform.
93 */
94
95 public static DateTimeValue now() {
96 return DateTimeValue.fromZonedDateTime(ZonedDateTime.now());
97 }
98
99 /**
100 * Constructor: create a dateTime value given a Java calendar object.
101 * The {@code #hasNoYearZero} flag is set to {@code true}.
102 *
103 * @param calendar holds the date and time
104 * @param tzSpecified indicates whether the timezone is specified
105 */
106
107 public DateTimeValue(/*@NotNull*/ Calendar calendar, boolean tzSpecified) {
108 int era = calendar.get(GregorianCalendar.ERA);
109 year = calendar.get(Calendar.YEAR);
110 if (era == GregorianCalendar.BC) {
111 year = 1 - year;
112 }
113 month = (byte) (calendar.get(Calendar.MONTH) + 1);
114 day = (byte) calendar.get(Calendar.DATE);
115 hour = (byte) calendar.get(Calendar.HOUR_OF_DAY);
116 minute = (byte) calendar.get(Calendar.MINUTE);
117 second = (byte) calendar.get(Calendar.SECOND);
118 nanosecond = calendar.get(Calendar.MILLISECOND) * 1_000_000;
119 if (tzSpecified) {
120 int tz = (calendar.get(Calendar.ZONE_OFFSET) +
121 calendar.get(Calendar.DST_OFFSET)) / 60_000;
122 setTimezoneInMinutes(tz);
123 }
124 typeLabel = BuiltInAtomicType.DATE_TIME;
125 hasNoYearZero = true;
126 }
127
128 /**
129 * Factory method: create a dateTime value given a Java Date object. The returned dateTime
130 * value will always have a timezone, which will always be UTC.
131 *
132 * @param suppliedDate holds the date and time
133 * @return the corresponding xs:dateTime value
134 * @throws XPathException if a dynamic error occurs
135 */
136
137 /*@NotNull*/
138 public static DateTimeValue fromJavaDate(/*@NotNull*/ Date suppliedDate) throws XPathException {
139 long millis = suppliedDate.getTime();
140 return EPOCH.add(DayTimeDurationValue.fromMilliseconds(millis));
141 }
142
143 /**
144 * Factory method: create a dateTime value given a Java time, expressed in milliseconds since 1970. The returned dateTime
145 * value will always have a timezone, which will always be UTC.
146 *
147 * @param time the time in milliseconds since the epoch
148 * @return the corresponding xs:dateTime value
149 * @throws XPathException if a dynamic error occurs
150 */
151
152 /*@NotNull*/
153 public static DateTimeValue fromJavaTime(long time) throws XPathException {
154 return EPOCH.add(DayTimeDurationValue.fromMilliseconds(time));
155 }
156
157 /**
158 * Factory method: create a dateTime value given the components of a Java Instant. The java.time.Instant class
159 * is new in JDK 8, and this method was introduced under older JDKs, so this method takes two arguments,
160 * the seconds and nano-seconds values, which can be obtained from a Java Instant
161 * using the methods getEpochSecond() and getNano() respectively
162 *
163 * @param seconds the time in seconds since the epoch
164 * @param nano the additional nanoseconds
165 * @return the corresponding xs:dateTime value, which will have timezone Z (UTC)
166 * @throws XPathException if a dynamic error occurs (typically due to overflow)
167 */
168
169 /*@NotNull*/
170 public static DateTimeValue fromJavaInstant(long seconds, int nano) throws XPathException {
171 return EPOCH
172 .add(DayTimeDurationValue.fromSeconds(new BigDecimal(seconds))
173 .add(DayTimeDurationValue.fromNanoseconds(nano)));
174 }
175
176 /**
177 * Factory method: create a dateTime value given a Java {@link Instant}. The {@code java.time.Instant} class
178 * is new in JDK 8. Note that {@code DateTimeValue} only holds microsecond precision, so there will be some
179 * rounding.
180 *
181 * @param instant the point in time
182 * @return the corresponding xs:dateTime value, which will have timezone Z (UTC)
183 * @since 9.9
184 */
185
186 /*@NotNull*/
187 public static DateTimeValue fromJavaInstant(Instant instant) {
188 try {
189 return fromJavaInstant(instant.getEpochSecond(), instant.getNano());
190 } catch (XPathException e) {
191 throw new AssertionError();
192 }
193 }
194
195 /**
196 * Factory method: create a dateTime value given a Java {@link ZonedDateTime}. The {@code java.time.ZonedDateTime} class
197 * is new in JDK 8. Note that {@code DateTimeValue} only holds microsecond precision, so there will be some
198 * rounding.
199 *
200 * @param zonedDateTime the supplied zonedDateTime value
201 * @return the corresponding xs:dateTime value, which will have the same timezone offset as the supplied ZonedDateTime;
202 * the actual (civil) timezone information is lost. The returned value will be an instance of the built-in
203 * subtype {@code xs:dateTimeStamp}
204 * @since 9.9
205 */
206
207 /*@NotNull*/
208 public static DateTimeValue fromZonedDateTime(ZonedDateTime zonedDateTime) {
209 LocalDateTime ldt = zonedDateTime.toLocalDateTime();
210 ZoneOffset zo = zonedDateTime.getOffset();
211 int tz = zo.getTotalSeconds() / 60;
212 DateTimeValue dtv = new DateTimeValue(ldt.getYear(), (byte)ldt.getMonthValue(), (byte)ldt.getDayOfMonth(),
213 (byte)ldt.getHour(), (byte)ldt.getMinute(), (byte)ldt.getSecond(),
214 ldt.getNano()/1000, tz, false);
215 dtv.typeLabel = BuiltInAtomicType.DATE_TIME_STAMP;
216 return dtv;
217 }
218
219 /**
220 * Factory method: create a dateTime value given a Java {@link LocalDateTime}. The {@code java.time.LocalDateTime} class
221 * is new in JDK 8. Note that {@code DateTimeValue} only holds microsecond precision, so there will be some
222 * rounding.
223 *
224 * @param localDateTime the supplied localDateTime value
225 * @return the corresponding xs:dateTime value, which will have no timezone.
226 * @since 9.9
227 */
228
229 /*@NotNull*/
230 public static DateTimeValue fromLocalDateTime(LocalDateTime localDateTime) {
231 return new DateTimeValue(localDateTime.getYear(), (byte) localDateTime.getMonthValue(), (byte) localDateTime.getDayOfMonth(),
232 (byte) localDateTime.getHour(), (byte) localDateTime.getMinute(), (byte) localDateTime.getSecond(),
233 localDateTime.getNano() / 1000, NO_TIMEZONE, false);
234 }
235
236 /**
237 * Fixed date/time used by Java (and Unix) as the origin of the universe: 1970-01-01T00:00:00Z
238 */
239
240 /*@NotNull*/ public static final DateTimeValue EPOCH =
241 new DateTimeValue(1970, (byte) 1, (byte) 1, (byte) 0, (byte) 0, (byte) 0, 0, 0, true);
242
243 /**
244 * Factory method: create a dateTime value given a date and a time.
245 *
246 * @param date the date
247 * @param time the time
248 * @return the dateTime with the given components. If either component is null, returns null. The returned
249 * {@code DateTimeValue} will have the {@code #hasNoYearZero} property if and only if the supplied
250 * date has this property.
251 * @throws XPathException if the timezones are both present and inconsistent
252 */
253
254 /*@Nullable*/
255 public static DateTimeValue makeDateTimeValue(/*@Nullable*/ DateValue date, /*@Nullable*/ TimeValue time) throws XPathException {
256 if (date == null || time == null) {
257 return null;
258 }
259 int tz1 = date.getTimezoneInMinutes();
260 int tz2 = time.getTimezoneInMinutes();
261 if (tz1 != NO_TIMEZONE && tz2 != NO_TIMEZONE && tz1 != tz2) {
262 XPathException err = new XPathException("Supplied date and time are in different timezones");
263 err.setErrorCode("FORG0008");
264 throw err;
265 }
266
267 DateTimeValue v = date.toDateTime();
268 v.hour = time.getHour();
269 v.minute = time.getMinute();
270 v.second = time.getSecond();
271 v.nanosecond = time.getNanosecond();
272 v.setTimezoneInMinutes(Math.max(tz1, tz2));
273 v.typeLabel = BuiltInAtomicType.DATE_TIME;
274 v.hasNoYearZero = date.hasNoYearZero;
275 return v;
276 }
277
278 /**
279 * Factory method: create a dateTime value from a supplied string, in
280 * ISO 8601 format.
281 * <p>If the supplied {@link ConversionRules} object has {@link ConversionRules#isAllowYearZero()} returning
282 * true, then (a) a year value of zero is allowed in the supplied string, and (b) the {@code hasNoYearZero}
283 * property in the result is set to false. If {@link ConversionRules#isAllowYearZero()} returns false,
284 * the (a) the year value in the supplied string must not be zero, (b) a year value of -1 in the supplied
285 * string is interpreted as representing the year before year 1, and (c) the {@code hasNoYearZero} property
286 * in the result is set to true.</p>
287 *
288 * @param s a string in the lexical space of xs:dateTime
289 * @param rules the conversion rules to be used (determining whether year zero is allowed)
290 * @return either a DateTimeValue representing the xs:dateTime supplied, or a ValidationFailure if
291 * the lexical value was invalid
292 */
293
294 /*@NotNull*/
295 public static ConversionResult makeDateTimeValue(CharSequence s, /*@NotNull*/ ConversionRules rules) {
296 // input must have format [-]yyyy-mm-ddThh:mm:ss[.fff*][([+|-]hh:mm | Z)]
297 DateTimeValue dt = new DateTimeValue();
298 dt.hasNoYearZero = !rules.isAllowYearZero();
299 StringTokenizer tok = new StringTokenizer(Whitespace.trimWhitespace(s).toString(), "-:.+TZ", true);
300
301 if (!tok.hasMoreElements()) {
302 return badDate("too short", s);
303 }
304 String part = (String) tok.nextElement();
305 int era = +1;
306 if ("+".equals(part)) {
307 return badDate("Date must not start with '+' sign", s);
308 } else if ("-".equals(part)) {
309 era = -1;
310 if (!tok.hasMoreElements()) {
311 return badDate("No year after '-'", s);
312 }
313 part = (String) tok.nextElement();
314 }
315 int value = DurationValue.simpleInteger(part);
316 if (value < 0) {
317 if (value == -1) {
318 return badDate("Non-numeric year component", s);
319 } else {
320 return badDate("Year is outside the range that Saxon can handle", s, "FODT0001");
321 }
322 }
323 dt.year = value * era;
324 if (part.length() < 4) {
325 return badDate("Year is less than four digits", s);
326 }
327 if (part.length() > 4 && part.charAt(0) == '0') {
328 return badDate("When year exceeds 4 digits, leading zeroes are not allowed", s);
329 }
330 if (dt.year == 0 && !rules.isAllowYearZero()) {
331 return badDate("Year zero is not allowed", s);
332 }
333 if (era < 0 && !rules.isAllowYearZero()) {
334 dt.year++; // if year zero not allowed, -0001 is the year before +0001, represented as 0 internally.
335 }
336 if (!tok.hasMoreElements()) {
337 return badDate("Too short", s);
338 }
339 if (!"-".equals(tok.nextElement())) {
340 return badDate("Wrong delimiter after year", s);
341 }
342
343 if (!tok.hasMoreElements()) {
344 return badDate("Too short", s);
345 }
346 part = (String) tok.nextElement();
347 if (part.length() != 2) {
348 return badDate("Month must be two digits", s);
349 }
350 value = DurationValue.simpleInteger(part);
351 if (value < 0) {
352 return badDate("Non-numeric month component", s);
353 }
354 dt.month = (byte) value;
355 if (dt.month < 1 || dt.month > 12) {
356 return badDate("Month is out of range", s);
357 }
358
359 if (!tok.hasMoreElements()) {
360 return badDate("Too short", s);
361 }
362 if (!"-".equals(tok.nextElement())) {
363 return badDate("Wrong delimiter after month", s);
364 }
365 if (!tok.hasMoreElements()) {
366 return badDate("Too short", s);
367 }
368 part = (String) tok.nextElement();
369 if (part.length() != 2) {
370 return badDate("Day must be two digits", s);
371 }
372 value = DurationValue.simpleInteger(part);
373 if (value < 0) {
374 return badDate("Non-numeric day component", s);
375 }
376 dt.day = (byte) value;
377 if (dt.day < 1 || dt.day > 31) {
378 return badDate("Day is out of range", s);
379 }
380
381 if (!tok.hasMoreElements()) {
382 return badDate("Too short", s);
383 }
384 if (!"T".equals(tok.nextElement())) {
385 return badDate("Wrong delimiter after day", s);
386 }
387
388 if (!tok.hasMoreElements()) {
389 return badDate("Too short", s);
390 }
391 part = (String) tok.nextElement();
392 if (part.length() != 2) {
393 return badDate("Hour must be two digits", s);
394 }
395 value = DurationValue.simpleInteger(part);
396 if (value < 0) {
397 return badDate("Non-numeric hour component", s);
398 }
399 dt.hour = (byte) value;
400 if (dt.hour > 24) {
401 return badDate("Hour is out of range", s);
402 }
403
404 if (!tok.hasMoreElements()) {
405 return badDate("Too short", s);
406 }
407 if (!":".equals(tok.nextElement())) {
408 return badDate("Wrong delimiter after hour", s);
409 }
410
411 if (!tok.hasMoreElements()) {
412 return badDate("Too short", s);
413 }
414 part = (String) tok.nextElement();
415 if (part.length() != 2) {
416 return badDate("Minute must be two digits", s);
417 }
418 value = DurationValue.simpleInteger(part);
419 if (value < 0) {
420 return badDate("Non-numeric minute component", s);
421 }
422 dt.minute = (byte) value;
423 if (dt.minute > 59) {
424 return badDate("Minute is out of range", s);
425 }
426 if (dt.hour == 24 && dt.minute != 0) {
427 return badDate("If hour is 24, minute must be 00", s);
428 }
429 if (!tok.hasMoreElements()) {
430 return badDate("Too short", s);
431 }
432 if (!":".equals(tok.nextElement())) {
433 return badDate("Wrong delimiter after minute", s);
434 }
435
436 if (!tok.hasMoreElements()) {
437 return badDate("Too short", s);
438 }
439 part = (String) tok.nextElement();
440 if (part.length() != 2) {
441 return badDate("Second must be two digits", s);
442 }
443 value = DurationValue.simpleInteger(part);
444 if (value < 0) {
445 return badDate("Non-numeric second component", s);
446 }
447 dt.second = (byte) value;
448
449 if (dt.second > 59) {
450 return badDate("Second is out of range", s);
451 }
452 if (dt.hour == 24 && dt.second != 0) {
453 return badDate("If hour is 24, second must be 00", s);
454 }
455
456 int tz = 0;
457 boolean negativeTz = false;
458 int state = 0;
459 while (tok.hasMoreElements()) {
460 if (state == 9) {
461 return badDate("Characters after the end", s);
462 }
463 String delim = (String) tok.nextElement();
464 if (".".equals(delim)) {
465 if (state != 0) {
466 return badDate("Decimal separator occurs twice", s);
467 }
468 if (!tok.hasMoreElements()) {
469 return badDate("Decimal point must be followed by digits", s);
470 }
471 part = (String) tok.nextElement();
472 if (part.length() > 9 && part.matches("^[0-9]+$")) {
473 part = part.substring(0, 9);
474 }
475 value = DurationValue.simpleInteger(part);
476 if (value < 0) {
477 return badDate("Non-numeric fractional seconds component", s);
478 }
479 double fractionalSeconds = Double.parseDouble('.' + part);
480 int nanoSeconds = (int) Math.round(fractionalSeconds * 1_000_000_000);
481 if (nanoSeconds == 1_000_000_000) {
482 nanoSeconds--; // truncate fractional seconds to .999_999_999 if nanoseconds rounds to 1_000_000_000
483 }
484 dt.nanosecond = nanoSeconds;
485
486 if (dt.hour == 24 && dt.nanosecond != 0) {
487 return badDate("If hour is 24, fractional seconds must be 0", s);
488 }
489 state = 1;
490 } else if ("Z".equals(delim)) {
491 if (state > 1) {
492 return badDate("Z cannot occur here", s);
493 }
494 tz = 0;
495 state = 9; // we've finished
496 dt.setTimezoneInMinutes(0);
497 } else if ("+".equals(delim) || "-".equals(delim)) {
498 if (state > 1) {
499 return badDate(delim + " cannot occur here", s);
500 }
501 state = 2;
502 if (!tok.hasMoreElements()) {
503 return badDate("Missing timezone", s);
504 }
505 part = (String) tok.nextElement();
506 if (part.length() != 2) {
507 return badDate("Timezone hour must be two digits", s);
508 }
509 value = DurationValue.simpleInteger(part);
510 if (value < 0) {
511 return badDate("Non-numeric timezone hour component", s);
512 }
513 tz = value;
514 if (tz > 14) {
515 return badDate("Timezone is out of range (-14:00 to +14:00)", s);
516 }
517 tz *= 60;
518
519 if ("-".equals(delim)) {
520 negativeTz = true;
521 }
522
523 } else if (":".equals(delim)) {
524 if (state != 2) {
525 return badDate("Misplaced ':'", s);
526 }
527 state = 9;
528 part = (String) tok.nextElement();
529 value = DurationValue.simpleInteger(part);
530 if (value < 0) {
531 return badDate("Non-numeric timezone minute component", s);
532 }
533 int tzminute = value;
534 if (part.length() != 2) {
535 return badDate("Timezone minute must be two digits", s);
536 }
537 if (tzminute > 59) {
538 return badDate("Timezone minute is out of range", s);
539 }
540 if (Math.abs(tz) == 14 * 60 && tzminute != 0) {
541 return badDate("Timezone is out of range (-14:00 to +14:00)", s);
542 }
543 tz += tzminute;
544 if (negativeTz) {
545 tz = -tz;
546 }
547 dt.setTimezoneInMinutes(tz);
548 } else {
549 return badDate("Timezone format is incorrect", s);
550 }
551 }
552
553 if (state == 2 || state == 3) {
554 return badDate("Timezone incomplete", s);
555 }
556
557 boolean midnight = false;
558 if (dt.hour == 24) {
559 dt.hour = 0;
560 midnight = true;
561 }
562
563 // Check that this is a valid calendar date
564 if (!DateValue.isValidDate(dt.year, dt.month, dt.day)) {
565 return badDate("Non-existent date", s);
566 }
567
568 // Adjust midnight to 00:00:00 on the next day
569 if (midnight) {
570 DateValue t = DateValue.tomorrow(dt.year, dt.month, dt.day);
571 dt.year = t.getYear();
572 dt.month = t.getMonth();
573 dt.day = t.getDay();
574 }
575
576
577 dt.typeLabel = BuiltInAtomicType.DATE_TIME;
578 return dt;
579 }
580
581 /**
582 * Factory method: create a dateTime value from a supplied string, in ISO 8601 format, allowing
583 * a year value of 0 to represent the year before year 1 (that is, following the XSD 1.1 rules).
584 * <p>The {@code hasNoYearZero} property in the result is set to false.</p>
585 *
586 * @param s a string in the lexical space of xs:dateTime
587 * @return a DateTimeValue representing the xs:dateTime supplied, including a timezone offset if
588 * present in the lexical representation
589 * @throws DateTimeParseException if the format of the supplied string is invalid.
590 * @since 9.9
591 */
592
593 public static DateTimeValue parse(CharSequence s) throws DateTimeParseException {
594 ConversionResult result = makeDateTimeValue(s, ConversionRules.DEFAULT);
595 if (result instanceof ValidationFailure) {
596 throw new DateTimeParseException(((ValidationFailure) result).getMessage(), s, 0);
597 } else {
598 return (DateTimeValue)result;
599 }
600 }
601
602 private static ValidationFailure badDate(String msg, CharSequence value) {
603 ValidationFailure err = new ValidationFailure(
604 "Invalid dateTime value " + Err.wrap(value, Err.VALUE) + " (" + msg + ")");
605 err.setErrorCode("FORG0001");
606 return err;
607 }
608
609 private static ValidationFailure badDate(String msg, CharSequence value, String errorCode) {
610 ValidationFailure err = new ValidationFailure(
611 "Invalid dateTime value " + Err.wrap(value, Err.VALUE) + " (" + msg + ")");
612 err.setErrorCode(errorCode);
613 return err;
614 }
615
616 /**
617 * Constructor: construct a DateTimeValue from its components.
618 * This constructor performs no validation.
619 * <p>Note: this constructor accepts the fractional seconds value
620 * to nanosecond precision. It creates a DateTimeValue that follows XSD 1.1 conventions:
621 * that is, there is a year zero. This can be changed by setting the {@code hasNoYearZero} property.</p>
622 *
623 * @param year The year (the year before year 1 is year 0)
624 * @param month The month, 1-12
625 * @param day The day 1-31
626 * @param hour the hour value, 0-23
627 * @param minute the minutes value, 0-59
628 * @param second the seconds value, 0-59
629 * @param nanosecond the number of nanoseconds, 0-999_999_999
630 * @param tz the timezone displacement in minutes from UTC. Supply the value
631 * {@link CalendarValue#NO_TIMEZONE} if there is no timezone component.
632 */
633
634 public DateTimeValue(int year, byte month, byte day,
635 byte hour, byte minute, byte second, int nanosecond, int tz) {
636
637 this.hasNoYearZero = false;
638 this.year = year;
639 this.month = month;
640 this.day = day;
641 this.hour = hour;
642 this.minute = minute;
643 this.second = second;
644 this.nanosecond = nanosecond;
645 setTimezoneInMinutes(tz);
646 typeLabel = BuiltInAtomicType.DATE_TIME;
647 }
648
649 /**
650 * Constructor: construct a DateTimeValue from its components.
651 * This constructor performs no validation.
652 * <p>Note: for historic reasons, this constructor accepts the fractional seconds value
653 * only to microsecond precision. To get nanosecond precision, use the 8-argument constructor
654 * and set the XSD 1.0 option separately</p>
655 *
656 * @param year The year as held internally (so the year before year 1 is year 0)
657 * @param month The month, 1-12
658 * @param day The day 1-31
659 * @param hour the hour value, 0-23
660 * @param minute the minutes value, 0-59
661 * @param second the seconds value, 0-59
662 * @param microsecond the number of microseconds, 0-999999
663 * @param tz the timezone displacement in minutes from UTC. Supply the value
664 * {@link CalendarValue#NO_TIMEZONE} if there is no timezone component.
665 * @param hasNoYearZero true if the dateTime value should behave under XSD 1.0 rules, that is,
666 * negative dates assume there is no year zero. Note that regardless of this
667 * setting, the year argument is set on the basis that the year before +1 is
668 * supplied as zero; but if the hasNoYearZero flag is set, this value will be displayed
669 * with a year of -1, and {@link #getYear() will return -1}
670 */
671
672 public DateTimeValue(int year, byte month, byte day,
673 byte hour, byte minute, byte second, int microsecond, int tz, boolean hasNoYearZero) {
674
675 this.hasNoYearZero = hasNoYearZero;
676 this.year = year;
677 this.month = month;
678 this.day = day;
679 this.hour = hour;
680 this.minute = minute;
681 this.second = second;
682 this.nanosecond = microsecond*1000;
683 setTimezoneInMinutes(tz);
684 typeLabel = BuiltInAtomicType.DATE_TIME;
685 }
686
687 /**
688 * Determine the primitive type of the value. This delivers the same answer as
689 * getItemType().getPrimitiveItemType(). The primitive types are
690 * the 19 primitive types of XML Schema, plus xs:integer, xs:dayTimeDuration and xs:yearMonthDuration,
691 * and xs:untypedAtomic. For external objects, the result is AnyAtomicType.
692 */
693
694 /*@NotNull*/
695 public BuiltInAtomicType getPrimitiveType() {
696 return BuiltInAtomicType.DATE_TIME;
697 }
698
699 /**
700 * Get the year component, in its internal form (which allows a year zero)
701 *
702 * @return the year component
703 */
704
705 public int getYear() {
706 return year;
707 }
708
709 /**
710 * Get the month component, 1-12
711 *
712 * @return the month component
713 */
714
715 public byte getMonth() {
716 return month;
717 }
718
719 /**
720 * Get the day component, 1-31
721 *
722 * @return the day component
723 */
724
725 public byte getDay() {
726 return day;
727 }
728
729 /**
730 * Get the hour component, 0-23
731 *
732 * @return the hour component (never 24, even if the input was specified as 24:00:00)
733 */
734
735 public byte getHour() {
736 return hour;
737 }
738
739 /**
740 * Get the minute component, 0-59
741 *
742 * @return the minute component
743 */
744
745 public byte getMinute() {
746 return minute;
747 }
748
749 /**
750 * Get the second component, 0-59
751 *
752 * @return the second component
753 */
754
755 public byte getSecond() {
756 return second;
757 }
758
759 /**
760 * Get the microsecond component, 0-999999
761 *
762 * @return the nanosecond component divided by 1000, rounded towards zero
763 */
764
765 public int getMicrosecond() {
766 return nanosecond / 1000;
767 }
768
769 /**
770 * Get the nanosecond component, 0-999999
771 *
772 * @return the nanosecond component
773 */
774
775 public int getNanosecond() {
776 return nanosecond;
777 }
778
779 /**
780 * Convert the value to an xs:dateTime, retaining all the components that are actually present, and
781 * substituting conventional values for components that are missing. (This method does nothing in
782 * the case of xs:dateTime, but is there to implement a method in the {@link CalendarValue} interface).
783 *
784 * @return the value as an xs:dateTime
785 */
786
787 /*@NotNull*/
788 public DateTimeValue toDateTime() {
789 return this;
790 }
791
792 /**
793 * Ask whether this value uses the XSD 1.0 rules (which don't allow year zero) or the XSD 1.1 rules (which do).
794 *
795 * @return true if the value uses the XSD 1.0 rules
796 */
797
798 public boolean isXsd10Rules() {
799 return hasNoYearZero;
800 }
801
802 /**
803 * Check that the value can be handled in Saxon-JS
804 *
805 * @throws XPathException if it can't be handled in Saxon-JS
806 */
807
808 @Override
809 public void checkValidInJavascript() throws XPathException {
810 if (year <= 0 || year > 9999) {
811 throw new XPathException("Year out of range for Saxon-JS", "FODT0001");
812 }
813 }
814
815 /**
816 * Normalize the date and time to be in timezone Z.
817 *
818 * @param implicitTimezone used to supply the implicit timezone, used when the value has
819 * no explicit timezone
820 * @return in general, a new DateTimeValue in timezone Z, representing the same instant in time.
821 * Returns the original DateTimeValue if this is already in timezone Z.
822 * @throws NoDynamicContextException if the implicit timezone is needed and is CalendarValue.MISSING_TIMEZONE
823 * or CalendarValue.NO_TIMEZONE
824 */
825
826 /*@NotNull*/
827 public DateTimeValue adjustToUTC(int implicitTimezone) throws NoDynamicContextException {
828 if (hasTimezone()) {
829 return adjustTimezone(0);
830 } else {
831 if (implicitTimezone == CalendarValue.MISSING_TIMEZONE || implicitTimezone == CalendarValue.NO_TIMEZONE) {
832 throw new NoDynamicContextException("DateTime operation needs access to implicit timezone");
833 }
834 DateTimeValue dt = copyAsSubType(null);
835 dt.setTimezoneInMinutes(implicitTimezone);
836 return dt.adjustTimezone(0);
837 }
838 }
839
840 /**
841 * Get the Julian instant: a decimal value whose integer part is the Julian day number
842 * multiplied by the number of seconds per day,
843 * and whose fractional part is the fraction of the second.
844 * This method operates on the local time, ignoring the timezone. The caller should call normalize()
845 * before calling this method to get a normalized time.
846 *
847 * @return the Julian instant corresponding to this xs:dateTime value
848 */
849
850 public BigDecimal toJulianInstant() {
851 int julianDay = DateValue.getJulianDayNumber(year, month, day);
852 long julianSecond = julianDay * 24L * 60L * 60L;
853 julianSecond += ((hour * 60L + minute) * 60L) + second;
854 BigDecimal j = BigDecimal.valueOf(julianSecond);
855 if (nanosecond == 0) {
856 return j;
857 } else {
858 return j.add(BigDecimal.valueOf(nanosecond).divide(BigDecimalValue.BIG_DECIMAL_ONE_BILLION, 9, RoundingMode.HALF_EVEN));
859 }
860 }
861
862 /**
863 * Get the DateTimeValue corresponding to a given Julian instant
864 *
865 * @param instant the Julian instant: a decimal value whose integer part is the Julian day number
866 * multiplied by the number of seconds per day, and whose fractional part is the fraction of the second.
867 * @return the xs:dateTime value corresponding to the Julian instant. This will always be in timezone Z.
868 */
869
870 /*@NotNull*/
871 public static DateTimeValue fromJulianInstant(/*@NotNull*/ BigDecimal instant) {
872 BigInteger julianSecond = instant.toBigInteger();
873 BigDecimal nanoseconds = instant.subtract(new BigDecimal(julianSecond)).multiply(BigDecimalValue.BIG_DECIMAL_ONE_BILLION);
874 long js = julianSecond.longValue();
875 long jd = js / (24L * 60L * 60L);
876 DateValue date = DateValue.dateFromJulianDayNumber((int) jd);
877 js = js % (24L * 60L * 60L);
878 byte hour = (byte) (js / (60L * 60L));
879 js = js % (60L * 60L);
880 byte minute = (byte) (js / 60L);
881 js = js % 60L;
882 return new DateTimeValue(date.getYear(), date.getMonth(), date.getDay(),
883 hour, minute, (byte) js, nanoseconds.intValue(), 0);
884 }
885
886 /**
887 * Get a Java Calendar object representing the value of this DateTime. This will respect the timezone
888 * if there is one (provided the timezone is within the range supported by the {@code GregorianCalendar}
889 * class, which in practice means that it is not -14:00). If there is no timezone or if
890 * the timezone is out of range, the result will be in GMT.
891 *
892 * @return a Java GregorianCalendar object representing the value of this xs:dateTime value.
893 */
894
895 /*@NotNull*/
896 public GregorianCalendar getCalendar() {
897 int tz = hasTimezone() ? getTimezoneInMinutes() * 60000 : 0;
898 TimeZone zone = new SimpleTimeZone(tz, "LLL");
899 GregorianCalendar calendar = new GregorianCalendar(zone);
900 if (tz < calendar.getMinimum(Calendar.ZONE_OFFSET) || tz > calendar.getMaximum(Calendar.ZONE_OFFSET)) {
901 return adjustTimezone(0).getCalendar();
902 }
903 calendar.setGregorianChange(new Date(Long.MIN_VALUE));
904 calendar.setLenient(false);
905 int yr = year;
906 if (year <= 0) {
907 yr = hasNoYearZero ? 1 - year : 0 - year;
908 calendar.set(Calendar.ERA, GregorianCalendar.BC);
909 }
910 //noinspection MagicConstant
911 calendar.set(yr, month - 1, day, hour, minute, second);
912 calendar.set(Calendar.MILLISECOND, nanosecond / 1_000_000); // loses precision unavoidably
913 calendar.set(Calendar.ZONE_OFFSET, tz);
914 calendar.set(Calendar.DST_OFFSET, 0);
915 return calendar;
916 }
917
918 /**
919 * Get a Java 8 {@link Instant} corresponding to this date and time. The value will respect the time zone
920 * offset if present, or will assume UTC otherwise.
921 */
922
923 public Instant toJavaInstant() {
924 return Instant.from(this);
925 }
926
927 /**
928 * Get a Java 8 {@link ZonedDateTime} corresponding to this date and time. The value will respect the time zone
929 * offset if present, or will assume UTC otherwise.
930 * @return a {@code ZonedDateTime} representing this date and time, including its timezone if present, or
931 * interpreted as a UTC date/time otherwise.
932 * @since 9.9
933 */
934
935 public ZonedDateTime toZonedDateTime() {
936 if (hasTimezone()) {
937 return ZonedDateTime.from(this);
938 } else {
939 try {
940 return ZonedDateTime.from(adjustToUTC(0));
941 } catch (NoDynamicContextException e) {
942 throw new AssertionError(e);
943 }
944 }
945 }
946
947 /**
948 * Get a Java 8 {@link LocalDateTime} corresponding to this date and time. The value will ignore any timezone
949 * offset present in this value.
950 * @return a {@code LocalDateTime} equivalent to this date and time, discarding any time zone offset if present.
951 * @since 9.9
952 */
953
954 public LocalDateTime toLocalDateTime() {
955 return LocalDateTime.from(this);
956 }
957
958 /**
959 * Convert to string
960 *
961 * @return ISO 8601 representation. The value returned is the localized representation:
962 * that is it uses the timezone contained within the value itself. In the case
963 * of a year earlier than year 1, the value output is the internally-held year,
964 * unless the {@code hasNoYearZero} flag is set, in which case it is the
965 * internal year minus one.
966 */
967
968 /*@NotNull*/
969 public CharSequence getPrimitiveStringValue() {
970
971 FastStringBuffer sb = new FastStringBuffer(30);
972 int yr = year;
973 if (year <= 0) {
974 yr = -yr + (hasNoYearZero ? 1 : 0); // no year zero in lexical space for XSD 1.0
975 if (yr != 0) {
976 sb.append('-');
977 }
978 }
979 appendString(sb, yr, yr > 9999 ? (yr + "").length() : 4);
980 sb.append('-');
981 appendTwoDigits(sb, month);
982 sb.append('-');
983 appendTwoDigits(sb, day);
984 sb.append('T');
985 appendTwoDigits(sb, hour);
986 sb.append(':');
987 appendTwoDigits(sb, minute);
988 sb.append(':');
989 appendTwoDigits(sb, second);
990 if (nanosecond != 0) {
991 sb.append('.');
992 int ms = nanosecond;
993 int div = 100_000_000;
994 while (ms > 0) {
995 int d = ms / div;
996 sb.append((char) (d + '0'));
997 ms = ms % div;
998 div /= 10;
999 }
1000 }
1001
1002 if (hasTimezone()) {
1003 appendTimezone(sb);
1004 }
1005
1006 return sb;
1007
1008 }
1009
1010 /**
1011 * Extract the Date part
1012 *
1013 * @return a DateValue representing the date part of the dateTime, retaining the timezone or its absence
1014 */
1015
1016 /*@NotNull*/
1017 public DateValue toDateValue() {
1018 return new DateValue(year, month, day, getTimezoneInMinutes(), hasNoYearZero);
1019 }
1020
1021 /**
1022 * Extract the Time part
1023 *
1024 * @return a TimeValue representing the date part of the dateTime, retaining the timezone or its absence
1025 */
1026
1027 /*@NotNull*/
1028 public TimeValue toTimeValue() {
1029 return new TimeValue(hour, minute, second, nanosecond, getTimezoneInMinutes(), "");
1030 }
1031
1032
1033 /**
1034 * Get the canonical lexical representation as defined in XML Schema. This is not always the same
1035 * as the result of casting to a string according to the XPath rules. For an xs:dateTime it is the
1036 * date/time adjusted to UTC.
1037 *
1038 * @return the canonical lexical representation as defined in XML Schema
1039 */
1040
1041 public CharSequence getCanonicalLexicalRepresentation() {
1042 if (hasTimezone() && getTimezoneInMinutes() != 0) {
1043 return adjustTimezone(0).getStringValueCS();
1044 } else {
1045 return getStringValueCS();
1046 }
1047 }
1048
1049 /**
1050 * Make a copy of this date, time, or dateTime value, but with a new type label
1051 *
1052 * @param typeLabel the type label to be attached to the new copy. It is the caller's responsibility
1053 * to ensure that the value actually conforms to the rules for this type.
1054 */
1055
1056 /*@NotNull*/
1057 public DateTimeValue copyAsSubType(AtomicType typeLabel) {
1058 DateTimeValue v = new DateTimeValue(year, month, day,
1059 hour, minute, second, nanosecond, getTimezoneInMinutes());
1060 v.hasNoYearZero = hasNoYearZero;
1061 v.typeLabel = typeLabel;
1062 return v;
1063 }
1064
1065 /**
1066 * Return a new dateTime with the same normalized value, but
1067 * in a different timezone.
1068 *
1069 * @param timezone the new timezone offset, in minutes
1070 * @return the date/time in the new timezone. This will be a new DateTimeValue unless no change
1071 * was required to the original value
1072 */
1073
1074 /*@NotNull*/
1075 public DateTimeValue adjustTimezone(int timezone) {
1076 if (!hasTimezone()) {
1077 DateTimeValue in = copyAsSubType(typeLabel);
1078 in.setTimezoneInMinutes(timezone);
1079 return in;
1080 }
1081 int oldtz = getTimezoneInMinutes();
1082 if (oldtz == timezone) {
1083 return this;
1084 }
1085 int tz = timezone - oldtz;
1086 int h = hour;
1087 int mi = minute;
1088 mi += tz;
1089 if (mi < 0 || mi > 59) {
1090 h += Math.floor(mi / 60.0);
1091 mi = (mi + 60 * 24) % 60;
1092 }
1093
1094 if (h >= 0 && h < 24) {
1095 DateTimeValue d2 = new DateTimeValue(year, month, day, (byte) h, (byte) mi, second, nanosecond, timezone);
1096 d2.hasNoYearZero = hasNoYearZero;
1097 return d2;
1098 }
1099
1100 // Following code is designed to handle the corner case of adjusting from -14:00 to +14:00 or
1101 // vice versa, which can cause a change of two days in the date
1102 DateTimeValue dt = this;
1103 while (h < 0) {
1104 h += 24;
1105 DateValue t = DateValue.yesterday(dt.getYear(), dt.getMonth(), dt.getDay());
1106 dt = new DateTimeValue(t.getYear(), t.getMonth(), t.getDay(),
1107 (byte) h, (byte) mi, second, nanosecond, timezone);
1108 dt.hasNoYearZero = hasNoYearZero;
1109 }
1110 if (h > 23) {
1111 h -= 24;
1112 DateValue t = DateValue.tomorrow(year, month, day);
1113 dt = new DateTimeValue(t.getYear(), t.getMonth(), t.getDay(),
1114 (byte) h, (byte) mi, second, nanosecond, timezone);
1115 dt.hasNoYearZero = hasNoYearZero;
1116 }
1117 return dt;
1118 }
1119
1120 /**
1121 * Add a duration to a dateTime
1122 *
1123 * @param duration the duration to be added (may be negative)
1124 * @return the new date
1125 * @throws net.sf.saxon.trans.XPathException
1126 * if the duration is an xs:duration, as distinct from
1127 * a subclass thereof
1128 */
1129
1130 /*@NotNull*/
1131 public DateTimeValue add(/*@NotNull*/ DurationValue duration) throws XPathException {
1132 if (duration instanceof DayTimeDurationValue) {
1133 BigDecimal seconds = ((DayTimeDurationValue) duration).getTotalSeconds();
1134 BigDecimal julian = toJulianInstant();
1135 julian = julian.add(seconds);
1136 DateTimeValue dt = fromJulianInstant(julian);
1137 dt.setTimezoneInMinutes(getTimezoneInMinutes());
1138 dt.hasNoYearZero = this.hasNoYearZero;
1139 return dt;
1140 } else if (duration instanceof YearMonthDurationValue) {
1141 int months = ((YearMonthDurationValue) duration).getLengthInMonths();
1142 int m = (month - 1) + months;
1143 int y = year + m / 12;
1144 m = m % 12;
1145 if (m < 0) {
1146 m += 12;
1147 y -= 1;
1148 }
1149 m++;
1150 int d = day;
1151 while (!DateValue.isValidDate(y, m, d)) {
1152 d -= 1;
1153 }
1154 DateTimeValue dtv = new DateTimeValue(y, (byte) m, (byte) d,
1155 hour, minute, second, nanosecond, getTimezoneInMinutes());
1156 dtv.hasNoYearZero = hasNoYearZero;
1157 return dtv;
1158 } else {
1159 XPathException err = new XPathException("DateTime arithmetic is not supported on xs:duration, only on its subtypes");
1160 err.setErrorCode("XPTY0004");
1161 err.setIsTypeError(true);
1162 throw err;
1163 }
1164 }
1165
1166 /**
1167 * Determine the difference between two points in time, as a duration
1168 *
1169 * @param other the other point in time
1170 * @param context the XPath dynamic context
1171 * @return the duration as an xs:dayTimeDuration
1172 * @throws net.sf.saxon.trans.XPathException
1173 * for example if one value is a date and the other is a time
1174 */
1175
1176 public DayTimeDurationValue subtract(/*@NotNull*/ CalendarValue other, XPathContext context) throws XPathException {
1177 if (!(other instanceof DateTimeValue)) {
1178 XPathException err = new XPathException("First operand of '-' is a dateTime, but the second is not");
1179 err.setErrorCode("XPTY0004");
1180 err.setIsTypeError(true);
1181 throw err;
1182 }
1183 return super.subtract(other, context);
1184 }
1185
1186 public BigDecimal secondsSinceEpoch() {
1187 try {
1188 DateTimeValue dtv = adjustToUTC(0);
1189 BigDecimal d1 = dtv.toJulianInstant();
1190 BigDecimal d2 = EPOCH.toJulianInstant();
1191 return d1.subtract(d2);
1192 } catch (NoDynamicContextException e) {
1193 throw new AssertionError(e);
1194 }
1195 }
1196
1197 /**
1198 * Get a component of the value. Returns null if the timezone component is
1199 * requested and is not present.
1200 * @param component identifies the required component
1201 */
1202
1203 /*@Nullable*/
1204 public AtomicValue getComponent(AccessorFn.Component component) throws XPathException {
1205 switch (component) {
1206 case YEAR_ALLOWING_ZERO:
1207 return Int64Value.makeIntegerValue(year);
1208 case YEAR:
1209 return Int64Value.makeIntegerValue(year > 0 || !hasNoYearZero ? year : year - 1);
1210 case MONTH:
1211 return Int64Value.makeIntegerValue(month);
1212 case DAY:
1213 return Int64Value.makeIntegerValue(day);
1214 case HOURS:
1215 return Int64Value.makeIntegerValue(hour);
1216 case MINUTES:
1217 return Int64Value.makeIntegerValue(minute);
1218 case SECONDS:
1219 BigDecimal d = BigDecimal.valueOf(nanosecond);
1220 d = d.divide(BigDecimalValue.BIG_DECIMAL_ONE_BILLION, 6, BigDecimal.ROUND_HALF_UP);
1221 d = d.add(BigDecimal.valueOf(second));
1222 return new BigDecimalValue(d);
1223 case WHOLE_SECONDS: //(internal use only)
1224 return Int64Value.makeIntegerValue(second);
1225 case MICROSECONDS:
1226 // internal use only
1227 return new Int64Value(nanosecond / 1000);
1228 case NANOSECONDS:
1229 // internal use only
1230 return new Int64Value(nanosecond);
1231 case TIMEZONE:
1232 if (hasTimezone()) {
1233 return DayTimeDurationValue.fromMilliseconds(60000L * getTimezoneInMinutes());
1234 } else {
1235 return null;
1236 }
1237 default:
1238 throw new IllegalArgumentException("Unknown component for dateTime: " + component);
1239 }
1240 }
1241
1242 @Override
1243 public boolean isSupported(TemporalField field) {
1244 if (field.equals(ChronoField.OFFSET_SECONDS)) {
1245 return getTimezoneInMinutes() != NO_TIMEZONE;
1246 } else if (field instanceof ChronoField) {
1247 return true;
1248 } else {
1249 return field.isSupportedBy(this);
1250 }
1251 }
1252
1253 /**
1254 * Gets the value of the specified field as a {@code long}.
1255 * <p>This queries the date-time for the value of the specified field.
1256 * The returned value may be outside the valid range of values for the field.
1257 * If the date-time cannot return the value, because the field is unsupported or for
1258 * some other reason, an exception will be thrown.</p>
1259 *
1260 * <p>The specification requires some fields (for example {@link ChronoField#EPOCH_DAY} to
1261 * reflect the local time. The Saxon implementation does not have access to the local time,
1262 * so it adjusts to UTC instead.</p>
1263 *
1264 * @param field the field to get, not null
1265 * @return the value for the field
1266 * @throws DateTimeException if a value for the field cannot be obtained
1267 * @throws UnsupportedTemporalTypeException if the field is not supported
1268 * @throws ArithmeticException if numeric overflow occurs
1269 * @implSpec Implementations must check and handle all fields defined in {@link ChronoField}.
1270 * If the field is supported, then the value of the field must be returned.
1271 * If unsupported, then an {@code UnsupportedTemporalTypeException} must be thrown.
1272 * <p>If the field is not a {@code ChronoField}, then the result of this method
1273 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
1274 * passing {@code this} as the argument.</p>
1275 * <p>Implementations must ensure that no observable state is altered when this
1276 * read-only method is invoked.</p>
1277 */
1278
1279 @Override
1280 public long getLong(TemporalField field) {
1281 if (field instanceof ChronoField) {
1282 switch ((ChronoField) field) {
1283 case NANO_OF_SECOND:
1284 return nanosecond;
1285 case NANO_OF_DAY:
1286 return (hour * 3600 + minute * 60 + second) * 1_000_000_000L + nanosecond;
1287 case MICRO_OF_SECOND:
1288 return nanosecond / 1000;
1289 case MICRO_OF_DAY:
1290 return (hour * 3600 + minute * 60 + second) * 1_000_000L + (nanosecond / 1000);
1291 case MILLI_OF_SECOND:
1292 return nanosecond / 1_000_000;
1293 case MILLI_OF_DAY:
1294 return (hour * 3600 + minute * 60 + second)*1000L + nanosecond / 1_000_000;
1295 case SECOND_OF_MINUTE:
1296 return second;
1297 case SECOND_OF_DAY:
1298 return hour*3600 + minute*60 + second;
1299 case MINUTE_OF_HOUR:
1300 return minute;
1301 case MINUTE_OF_DAY:
1302 return hour*60 + minute;
1303 case HOUR_OF_AMPM:
1304 return hour%12;
1305 case CLOCK_HOUR_OF_AMPM:
1306 return (hour+11)%12 + 1;
1307 case HOUR_OF_DAY:
1308 return hour;
1309 case CLOCK_HOUR_OF_DAY:
1310 return (hour+23)%24 + 1;
1311 case AMPM_OF_DAY:
1312 return hour/12; // specification is unclear about noon and midnight
1313 case DAY_OF_WEEK:
1314 return DateValue.getDayOfWeek(year, month, day);
1315 case ALIGNED_DAY_OF_WEEK_IN_MONTH:
1316 return (day - 1) % 7 + 1;
1317 case ALIGNED_DAY_OF_WEEK_IN_YEAR:
1318 return (DateValue.getDayWithinYear(year, month, day) - 1) % 7 + 1;
1319 case DAY_OF_MONTH:
1320 return day;
1321 case DAY_OF_YEAR:
1322 return DateValue.getDayWithinYear(year, month, day);
1323 case EPOCH_DAY:
1324 BigDecimal secs = secondsSinceEpoch();
1325 long days = secondsSinceEpoch().longValue() / (24*60*60);
1326 return secs.signum() < 0 ? days-1 : days;
1327 case ALIGNED_WEEK_OF_MONTH:
1328 return (day - 1) / 7 + 1;
1329 case ALIGNED_WEEK_OF_YEAR:
1330 return (DateValue.getDayWithinYear(year, month, day) - 1) / 7 + 1;
1331 case MONTH_OF_YEAR:
1332 return month;
1333 case PROLEPTIC_MONTH:
1334 return year*12 + month - 1;
1335 case YEAR_OF_ERA:
1336 return Math.abs(year) + (year<0 ? 1 : 0);
1337 case YEAR:
1338 return year;
1339 case ERA:
1340 return year<0 ? 0 : 1;
1341 case INSTANT_SECONDS:
1342 return secondsSinceEpoch().setScale(0, BigDecimal.ROUND_FLOOR).longValue();
1343 case OFFSET_SECONDS:
1344 int tz = getTimezoneInMinutes();
1345 if (tz == NO_TIMEZONE) {
1346 throw new UnsupportedTemporalTypeException("xs:dateTime value has no timezone");
1347 } else {
1348 return tz * 60;
1349 }
1350 default:
1351 throw new UnsupportedTemporalTypeException(field.toString());
1352 }
1353 } else {
1354 return field.getFrom(this);
1355 }
1356 }
1357
1358 /**
1359 * Compare the value to another dateTime value, following the XPath comparison semantics
1360 *
1361 * @param other The other dateTime value
1362 * @param implicitTimezone The implicit timezone to be used for a value with no timezone
1363 * @return negative value if this one is the earler, 0 if they are chronologically equal,
1364 * positive value if this one is the later. For this purpose, dateTime values with an unknown
1365 * timezone are considered to be values in the implicit timezone (the Comparable interface requires
1366 * a total ordering).
1367 * @throws ClassCastException if the other value is not a DateTimeValue (the parameter
1368 * is declared as CalendarValue to satisfy the interface)
1369 * @throws NoDynamicContextException if the implicit timezone is needed and is not available
1370 */
1371
1372 public int compareTo(/*@NotNull*/ CalendarValue other, int implicitTimezone) throws NoDynamicContextException {
1373 if (!(other instanceof DateTimeValue)) {
1374 throw new ClassCastException("DateTime values are not comparable to " + other.getClass());
1375 }
1376 DateTimeValue v2 = (DateTimeValue) other;
1377 if (getTimezoneInMinutes() == v2.getTimezoneInMinutes()) {
1378 // both values are in the same timezone (explicitly or implicitly)
1379 if (year != v2.year) {
1380 return IntegerValue.signum(year - v2.year);
1381 }
1382 if (month != v2.month) {
1383 return IntegerValue.signum(month - v2.month);
1384 }
1385 if (day != v2.day) {
1386 return IntegerValue.signum(day - v2.day);
1387 }
1388 if (hour != v2.hour) {
1389 return IntegerValue.signum(hour - v2.hour);
1390 }
1391 if (minute != v2.minute) {
1392 return IntegerValue.signum(minute - v2.minute);
1393 }
1394 if (second != v2.second) {
1395 return IntegerValue.signum(second - v2.second);
1396 }
1397 if (nanosecond != v2.nanosecond) {
1398 return IntegerValue.signum(nanosecond - v2.nanosecond);
1399 }
1400 return 0;
1401 }
1402 return adjustToUTC(implicitTimezone).compareTo(v2.adjustToUTC(implicitTimezone), implicitTimezone);
1403 }
1404
1405 /**
1406 * Context-free comparison of two DateTimeValue values. For this to work,
1407 * the two values must either both have a timezone or both have none.
1408 *
1409 * @param v2 the other value
1410 * @return the result of the comparison: -1 if the first is earlier, 0 if they
1411 * are equal, +1 if the first is later
1412 * @throws ClassCastException if the values are not comparable (which might be because
1413 * no timezone is available)
1414 */
1415
1416 public int compareTo(Object v2) {
1417 try {
1418 return compareTo((DateTimeValue) v2, MISSING_TIMEZONE);
1419 } catch (Exception err) {
1420 throw new ClassCastException("DateTime comparison requires access to implicit timezone");
1421 }
1422 }
1423
1424 /*@NotNull*/
1425 public Comparable getSchemaComparable() {
1426 return new DateTimeComparable();
1427 }
1428
1429 /**
1430 * DateTimeComparable is an object that implements the XML Schema rules for comparing date/time values
1431 */
1432
1433 private class DateTimeComparable implements Comparable {
1434
1435 /*@NotNull*/
1436 private DateTimeValue asDateTimeValue() {
1437 return DateTimeValue.this;
1438 }
1439
1440 // Rules from XML Schema Part 2
1441 public int compareTo(/*@NotNull*/ Object o) {
1442 if (o instanceof DateTimeComparable) {
1443 DateTimeValue dt0 = DateTimeValue.this;
1444 DateTimeValue dt1 = ((DateTimeComparable) o).asDateTimeValue();
1445 if (dt0.hasTimezone()) {
1446 if (dt1.hasTimezone()) {
1447 dt0 = dt0.adjustTimezone(0);
1448 dt1 = dt1.adjustTimezone(0);
1449 return dt0.compareTo(dt1);
1450 } else {
1451 DateTimeValue dt1max = dt1.adjustTimezone(14 * 60);
1452 if (dt0.compareTo(dt1max) < 0) {
1453 return -1;
1454 }
1455 DateTimeValue dt1min = dt1.adjustTimezone(-14 * 60);
1456 if (dt0.compareTo(dt1min) > 0) {
1457 return +1;
1458 }
1459 return SequenceTool.INDETERMINATE_ORDERING;
1460 }
1461 } else {
1462 if (dt1.hasTimezone()) {
1463 DateTimeValue dt0min = dt0.adjustTimezone(-14 * 60);
1464 if (dt0min.compareTo(dt1) < 0) {
1465 return -1;
1466 }
1467 DateTimeValue dt0max = dt0.adjustTimezone(14 * 60);
1468 if (dt0max.compareTo(dt1) > 0) {
1469 return +1;
1470 }
1471 return SequenceTool.INDETERMINATE_ORDERING;
1472 } else {
1473 dt0 = dt0.adjustTimezone(0);
1474 dt1 = dt1.adjustTimezone(0);
1475 return dt0.compareTo(dt1);
1476 }
1477 }
1478
1479 } else {
1480 return SequenceTool.INDETERMINATE_ORDERING;
1481 }
1482 }
1483
1484 public boolean equals(/*@NotNull*/ Object o) {
1485 return o instanceof DateTimeComparable &&
1486 DateTimeValue.this.hasTimezone() == ((DateTimeComparable) o).asDateTimeValue().hasTimezone() &&
1487 compareTo(o) == 0;
1488 }
1489
1490 public int hashCode() {
1491 DateTimeValue dt0 = adjustTimezone(0);
1492 return (dt0.year << 20) ^ (dt0.month << 16) ^ (dt0.day << 11) ^
1493 (dt0.hour << 7) ^ (dt0.minute << 2) ^ (dt0.second * 1_000_000_000 + dt0.nanosecond);
1494 }
1495 }
1496
1497 /**
1498 * Context-free comparison of two dateTime values
1499 *
1500 * @param o the other date time value
1501 * @return true if the two values represent the same instant in time. Return false if one value has
1502 * a timezone and the other does not (this is the result needed when using keys in a map)
1503 */
1504
1505 public boolean equals(Object o) {
1506 return o instanceof DateTimeValue && compareTo(o) == 0;
1507 }
1508
1509 /**
1510 * Hash code for context-free comparison of date time values. Note that equality testing
1511 * and therefore hashCode() works only for values with a timezone
1512 *
1513 * @return a hash code
1514 */
1515
1516 public int hashCode() {
1517 return hashCode(year, month, day, hour, minute, second, nanosecond, getTimezoneInMinutes());
1518 }
1519
1520 static int hashCode(int year, byte month, byte day, byte hour, byte minute, byte second, int nanosecond, int tzMinutes) {
1521 int tz = tzMinutes == CalendarValue.NO_TIMEZONE ? 0 : -tzMinutes;
1522 int h = hour;
1523 int mi = minute;
1524 mi += tz;
1525 if (mi < 0 || mi > 59) {
1526 h += Math.floor(mi / 60.0);
1527 mi = (mi + 60 * 24) % 60;
1528 }
1529 while (h < 0) {
1530 h += 24;
1531 DateValue t = DateValue.yesterday(year, month, day);
1532 year = t.getYear();
1533 month = t.getMonth();
1534 day = t.getDay();
1535 }
1536 while (h > 23) {
1537 h -= 24;
1538 DateValue t = DateValue.tomorrow(year, month, day);
1539 year = t.getYear();
1540 month = t.getMonth();
1541 day = t.getDay();
1542 }
1543 return (year << 4) ^ (month << 28) ^ (day << 23) ^ (h << 18) ^ (mi << 13) ^ second ^ nanosecond;
1544
1545 }
1546
1547 }
1548