Debian Codegraph @

net/sf/saxon/value/DateValue.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.expr.XPathContext;
11 import net.sf.saxon.lib.ConversionRules;
12 import net.sf.saxon.trans.XPathException;
13 import net.sf.saxon.tree.util.FastStringBuffer;
14 import net.sf.saxon.type.*;
15
16 import java.time.LocalDate;
17 import java.time.format.DateTimeParseException;
18 import java.time.temporal.WeekFields;
19 import java.util.Calendar;
20 import java.util.GregorianCalendar;
21
22 /**
23 * A value of type Date. Note that a Date may include a TimeZone.
24 */
25
26 public class DateValue extends GDateValue implements Comparable {
27
28 /**
29 * Private constructor of a skeletal DateValue
30 */
31
32 private DateValue() {
33 }
34
35 /**
36 * Constructor given a year, month, and day. Performs no validation.
37 *
38 * @param year The year as held internally (note that the year before 1AD is supplied as 0,
39 * but will be displayed on output as -0001)
40 * @param month The month, 1-12
41 * @param day The day, 1-31
42 */
43
44 public DateValue(int year, byte month, byte day) {
45 this.hasNoYearZero = true;
46 this.year = year;
47 this.month = month;
48 this.day = day;
49 typeLabel = BuiltInAtomicType.DATE;
50 }
51
52 /**
53 * Constructor given a year, month, day and xsd10. Performs no validation.
54 *
55 * @param year The year as held internally (note that the year before 1AD is supplied as 0)
56 * @param month The month, 1-12
57 * @param day The day, 1-31
58 * @param xsd10 Schema version flag. If set to true, the year before 1AD is displayed as -0001;
59 * if false, it is displayed as 0000; but in both cases, it is held internally as zero. The flag
60 * makes no difference to dates later than 1AD.
61 */
62
63 public DateValue(int year, byte month, byte day, boolean xsd10) {
64 this.hasNoYearZero = xsd10;
65 this.year = year;
66 this.month = month;
67 this.day = day;
68 typeLabel = BuiltInAtomicType.DATE;
69 }
70
71 /**
72 * Constructor given a year, month, and day, and timezone. Performs no validation.
73 *
74 * @param year The year as held internally (note that the year before 1AD is 0)
75 * @param month The month, 1-12
76 * @param day The day, 1-31
77 * @param tz the timezone displacement in minutes from UTC. Supply the value
78 * {@link CalendarValue#NO_TIMEZONE} if there is no timezone component.
79 * @param xsd10 Schema version flag. If set to true, the year before 1AD is displayed as -0001;
80 * if false, it is displayed as 0000; but in both cases, it is held internally as zero. The flag
81 * makes no difference to dates later than 1AD.
82 */
83
84 public DateValue(int year, byte month, byte day, int tz, boolean xsd10) {
85 // Method is called by generated Java code.
86 this.hasNoYearZero = xsd10;
87 this.year = year;
88 this.month = month;
89 this.day = day;
90 setTimezoneInMinutes(tz);
91 typeLabel = BuiltInAtomicType.DATE;
92 }
93
94 /**
95 * Constructor given a year, month, and day, and timezone, and an AtomicType representing
96 * a subtype of xs:date. Performs no validation.
97 *
98 * @param year The year as held internally (note that the year before 1AD is 0)
99 * @param month The month, 1-12
100 * @param day The day 1-31
101 * @param tz the timezone displacement in minutes from UTC. Supply the value
102 * {@link CalendarValue#NO_TIMEZONE} if there is no timezone component.
103 * @param type the type. This must be a type derived from xs:date, and the value
104 * must conform to this type. The method does not check these conditions.
105 */
106
107 public DateValue(int year, byte month, byte day, int tz, AtomicType type) {
108 this.year = year;
109 this.month = month;
110 this.day = day;
111 setTimezoneInMinutes(tz);
112 typeLabel = type;
113 }
114
115 /**
116 * Constructor: create a date value from a supplied string, in
117 * ISO 8601 format
118 *
119 * @param s the lexical form of the date value. Currently this assumes XSD 1.0
120 * conventions for BC years (that is, no year zero), but this may change at some time.
121 * @throws ValidationException if the supplied string is not a valid date
122 */
123 public DateValue(CharSequence s) throws ValidationException {
124 this(s, ConversionRules.DEFAULT);
125 }
126
127 /**
128 * Constructor: create a date value from a supplied string, in
129 * ISO 8601 format
130 *
131 * @param s the lexical form of the date value
132 * @param rules the conversion rules (determining whether year zero is allowed)
133 * @throws ValidationException if the supplied string is not a valid date
134 */
135 public DateValue(CharSequence s, ConversionRules rules) throws ValidationException {
136 setLexicalValue(this, s, rules.isAllowYearZero()).asAtomic();
137 typeLabel = BuiltInAtomicType.DATE;
138 }
139
140 /**
141 * Create a DateValue
142 *
143 * @param calendar the absolute date/time value
144 * @param tz The timezone offset from GMT in minutes, positive or negative; or the special
145 * value NO_TIMEZONE indicating that the value is not in a timezone
146 */
147 public DateValue(GregorianCalendar calendar, int tz) {
148 // Note: this constructor is not used by Saxon itself, but might be used by applications
149 int era = calendar.get(GregorianCalendar.ERA);
150 year = calendar.get(Calendar.YEAR);
151 if (era == GregorianCalendar.BC) {
152 year = 1 - year;
153 }
154 month = (byte) (calendar.get(Calendar.MONTH) + 1);
155 day = (byte) calendar.get(Calendar.DATE);
156 setTimezoneInMinutes(tz);
157 typeLabel = BuiltInAtomicType.DATE;
158 }
159
160 /**
161 * Static factory method: construct a DateValue from a string in the lexical form
162 * of a date, returning a ValidationFailure if the supplied string is invalid
163 *
164 * @param in the lexical form of the date
165 * @param rules conversion rules to apply (affects handling of year 0)
166 * @return either a DateValue or a ValidationFailure
167 */
168
169 public static ConversionResult makeDateValue(CharSequence in, ConversionRules rules) {
170 DateValue d = new DateValue();
171 d.typeLabel = BuiltInAtomicType.DATE;
172 return setLexicalValue(d, in, rules.isAllowYearZero());
173 }
174
175 /**
176 * Factory method: create an xs:date value from a supplied string, in ISO 8601 format, allowing
177 * a year value of 0 to represent the year before year 1 (that is, following the XSD 1.1 rules).
178 * <p>The {@code hasNoYearZero} property in the result is set to false.</p>
179 *
180 * @param s a string in the lexical space of xs:date
181 * @return a DateValue representing the xs:date supplied, including a timezone offset if
182 * present in the lexical representation
183 * @throws DateTimeParseException if the format of the supplied string is invalid.
184 * @since 9.9
185 */
186
187 public static DateValue parse(CharSequence s) throws DateTimeParseException {
188 ConversionResult result = makeDateValue(s, ConversionRules.DEFAULT);
189 if (result instanceof ValidationFailure) {
190 throw new DateTimeParseException(((ValidationFailure) result).getMessage(), s, 0);
191 } else {
192 return (DateValue) result;
193 }
194 }
195
196 /**
197 * Determine the primitive type of the value. This delivers the same answer as
198 * getItemType().getPrimitiveItemType(). The primitive types are
199 * the 19 primitive types of XML Schema, plus xs:integer, xs:dayTimeDuration and xs:yearMonthDuration,
200 * and xs:untypedAtomic. For external objects, the result is AnyAtomicType.
201 */
202
203 public BuiltInAtomicType getPrimitiveType() {
204 return BuiltInAtomicType.DATE;
205 }
206
207 /**
208 * Get the date that immediately follows a given date
209 *
210 * @param year the year
211 * @param month the month (1-12)
212 * @param day the day (1-31)
213 * @return a new DateValue with no timezone information
214 */
215
216 public static DateValue tomorrow(int year, byte month, byte day) {
217 if (DateValue.isValidDate(year, month, day + 1)) {
218 return new DateValue(year, month, (byte) (day + 1), true);
219 } else if (month < 12) {
220 return new DateValue(year, (byte) (month + 1), (byte) 1, true);
221 } else {
222 return new DateValue(year + 1, (byte) 1, (byte) 1, true);
223 }
224 }
225
226 /**
227 * Get the date that immediately precedes a given date
228 *
229 * @param year the year
230 * @param month the month (1-12)
231 * @param day the day (1-31)
232 * @return a new DateValue with no timezone information
233 */
234
235 public static DateValue yesterday(int year, byte month, byte day) {
236 if (day > 1) {
237 return new DateValue(year, month, (byte) (day - 1), true);
238 } else if (month > 1) {
239 if (month == 3 && isLeapYear(year)) {
240 return new DateValue(year, (byte) 2, (byte) 29, true);
241 } else {
242 return new DateValue(year, (byte) (month - 1), daysPerMonth[month - 2], true);
243 }
244 } else {
245 return new DateValue(year - 1, (byte) 12, (byte) 31, true);
246 }
247 }
248
249 /**
250 * Convert to string
251 *
252 * @return ISO 8601 representation.
253 */
254
255 public CharSequence getPrimitiveStringValue() {
256
257 FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C16);
258 int yr = year;
259 if (year <= 0) {
260 yr = -yr + (hasNoYearZero ? 1 : 0); // no year zero in lexical space for XSD 1.0
261 if (yr != 0) {
262 sb.append('-');
263 }
264 }
265 appendString(sb, yr, yr > 9999 ? (yr + "").length() : 4);
266 sb.append('-');
267 appendTwoDigits(sb, month);
268 sb.append('-');
269 appendTwoDigits(sb, day);
270
271 if (hasTimezone()) {
272 appendTimezone(sb);
273 }
274
275 return sb;
276
277 }
278
279 /**
280 * Get the canonical lexical representation as defined in XML Schema. This is not always the same
281 * as the result of casting to a string according to the XPath rules. For xs:date, the timezone is
282 * adjusted to be in the range +12:00 to -11:59
283 *
284 * @return the canonical lexical representation if defined in XML Schema; otherwise, the result
285 * of casting to string according to the XPath 2.0 rules
286 */
287
288 public CharSequence getCanonicalLexicalRepresentation() {
289 DateValue target = this;
290 if (hasTimezone()) {
291 if (getTimezoneInMinutes() > 12 * 60) {
292 target = adjustTimezone(getTimezoneInMinutes() - 24 * 60);
293 } else if (getTimezoneInMinutes() <= -12 * 60) {
294 target = adjustTimezone(getTimezoneInMinutes() + 24 * 60);
295 }
296 }
297 return target.getStringValueCS();
298 }
299
300 /**
301 * Make a copy of this date value, but with a new type label
302 *
303 * @param typeLabel the new type label: must be a subtype of xs:date
304 * @return the new xs:date value
305 */
306
307 /*@NotNull*/
308 public AtomicValue copyAsSubType(AtomicType typeLabel) {
309 DateValue v = new DateValue(year, month, day, getTimezoneInMinutes(), hasNoYearZero);
310 v.typeLabel = typeLabel;
311 return v;
312 }
313
314 /**
315 * Return a new date with the same normalized value, but
316 * in a different timezone. This is called only for a DateValue that has an explicit timezone
317 *
318 * @param timezone the new timezone offset, in minutes
319 * @return the time in the new timezone. This will be a new TimeValue unless no change
320 * was required to the original value
321 */
322
323 public DateValue adjustTimezone(int timezone) {
324 DateTimeValue dt = toDateTime().adjustTimezone(timezone);
325 return new DateValue(dt.getYear(), dt.getMonth(), dt.getDay(), dt.getTimezoneInMinutes(), hasNoYearZero);
326 }
327
328 /**
329 * Add a duration to a date
330 *
331 * @param duration the duration to be added (may be negative)
332 * @return the new date
333 * @throws net.sf.saxon.trans.XPathException
334 * if the duration is an xs:duration, as distinct from
335 * a subclass thereof
336 */
337
338 public DateValue add(DurationValue duration) throws XPathException {
339 if (duration instanceof DayTimeDurationValue) {
340 long microseconds = ((DayTimeDurationValue) duration).getLengthInMicroseconds();
341 boolean negative = microseconds < 0;
342 microseconds = Math.abs(microseconds);
343 int days = (int) Math.floor((double) microseconds / (1000000L * 60L * 60L * 24L));
344 boolean partDay = (microseconds % (1000000L * 60L * 60L * 24L)) > 0;
345 int julian = getJulianDayNumber();
346 DateValue d = dateFromJulianDayNumber(julian + (negative ? -days : days));
347 if (partDay) {
348 if (negative) {
349 d = yesterday(d.year, d.month, d.day);
350 }
351 }
352 d.setTimezoneInMinutes(getTimezoneInMinutes());
353 d.hasNoYearZero = this.hasNoYearZero;
354 return d;
355 } else if (duration instanceof YearMonthDurationValue) {
356 int months = ((YearMonthDurationValue) duration).getLengthInMonths();
357 int m = (month - 1) + months;
358 int y = year + m / 12;
359 m = m % 12;
360 if (m < 0) {
361 m += 12;
362 y -= 1;
363 }
364 m++;
365 int d = day;
366 while (!isValidDate(y, m, d)) {
367 d -= 1;
368 }
369 return new DateValue(y, (byte) m, (byte) d, getTimezoneInMinutes(), hasNoYearZero);
370 } else {
371 XPathException err = new XPathException("Date arithmetic is not available for xs:duration, only for its subtypes");
372 err.setIsTypeError(true);
373 err.setErrorCode("XPTY0004");
374 throw err;
375 }
376 }
377
378 /**
379 * Determine the difference between two points in time, as a duration
380 *
381 * @param other the other point in time
382 * @param context the XPath dynamic context. May be set to null
383 * only if both values contain an explicit timezone, or if neither does so.
384 * @return the duration as an xs:dayTimeDuration
385 * @throws XPathException for example if one value is a date and the other is a time
386 */
387
388 public DayTimeDurationValue subtract(/*@NotNull*/ CalendarValue other, /*@Nullable*/ XPathContext context) throws XPathException {
389 if (!(other instanceof DateValue)) {
390 XPathException err = new XPathException("First operand of '-' is a date, but the second is not");
391 err.setIsTypeError(true);
392 err.setErrorCode("XPTY0004");
393 throw err;
394 }
395 return super.subtract(other, context);
396 }
397
398
399 /**
400 * Context-free comparison of two DateValue values. For this to work,
401 * the two values must either both have a timezone or both have none.
402 *
403 * @param v2 the other value
404 * @return the result of the comparison: -1 if the first is earlier, 0 if they
405 * are equal, +1 if the first is later
406 * @throws ClassCastException if the values are not comparable (which might be because
407 * no timezone is available)
408 */
409
410 public int compareTo(Object v2) {
411 try {
412 return compareTo((DateValue) v2, MISSING_TIMEZONE);
413 } catch (Exception err) {
414 throw new ClassCastException("Date comparison requires access to implicit timezone");
415 }
416 }
417
418 /**
419 * Calculate the Julian day number at 00:00 on a given date. This algorithm is taken from
420 * http://vsg.cape.com/~pbaum/date/jdalg.htm and
421 * http://vsg.cape.com/~pbaum/date/jdalg2.htm
422 * (adjusted to handle BC dates correctly)
423 * <p>Note that this assumes dates in the proleptic Gregorian calendar</p>
424 *
425 * @param year the year
426 * @param month the month (1-12)
427 * @param day the day (1-31)
428 * @return the Julian day number
429 */
430
431 public static int getJulianDayNumber(int year, int month, int day) {
432 int z = year - (month < 3 ? 1 : 0);
433 short f = monthData[month - 1];
434 if (z >= 0) {
435 return day + f + 365 * z + z / 4 - z / 100 + z / 400 + 1721118;
436 } else {
437 // for negative years, add 12000 years and then subtract the days!
438 z += 12000;
439 int j = day + f + 365 * z + z / 4 - z / 100 + z / 400 + 1721118;
440 return j - (365 * 12000 + 12000 / 4 - 12000 / 100 + 12000 / 400); // number of leap years in 12000 years
441 }
442 }
443
444 /**
445 * Calculate the Julian day number at 00:00 on this date.
446 * <p>Note that this assumes dates in the proleptic Gregorian calendar</p>
447 *
448 * @return the Julian day number
449 */
450
451 public int getJulianDayNumber() {
452 return getJulianDayNumber(year, month, day);
453 }
454
455 /**
456 * Get the Gregorian date corresponding to a particular Julian day number. The algorithm
457 * is taken from http://www.hermetic.ch/cal_stud/jdn.htm#comp
458 *
459 * @param julianDayNumber the Julian day number
460 * @return a DateValue with no timezone information set
461 */
462
463 public static DateValue dateFromJulianDayNumber(int julianDayNumber) {
464 if (julianDayNumber >= 0) {
465 int L = julianDayNumber + 68569 + 1; // +1 adjustment for days starting at noon
466 int n = (4 * L) / 146097;
467 L = L - (146097 * n + 3) / 4;
468 int i = (4000 * (L + 1)) / 1461001;
469 L = L - (1461 * i) / 4 + 31;
470 int j = (80 * L) / 2447;
471 int d = L - (2447 * j) / 80;
472 L = j / 11;
473 int m = j + 2 - (12 * L);
474 int y = 100 * (n - 49) + i + L;
475 return new DateValue(y, (byte) m, (byte) d, true);
476 } else {
477 // add 12000 years and subtract them again...
478 DateValue dt = dateFromJulianDayNumber(julianDayNumber +
479 365 * 12000 + 12000 / 4 - 12000 / 100 + 12000 / 400);
480 dt.year -= 12000;
481 return dt;
482 }
483 }
484
485 /**
486 * Get the ordinal day number within the year (1 Jan = 1, 1 Feb = 32, etc)
487 *
488 * @param year the year
489 * @param month the month (1-12)
490 * @param day the day (1-31)
491 * @return the ordinal day number within the year
492 */
493
494 public static int getDayWithinYear(int year, int month, int day) {
495 int j = getJulianDayNumber(year, month, day);
496 int k = getJulianDayNumber(year, 1, 1);
497 return j - k + 1;
498 }
499
500 /**
501 * Get the day of the week. The days of the week are numbered from
502 * 1 (Monday) to 7 (Sunday)
503 *
504 * @param year the year
505 * @param month the month (1-12)
506 * @param day the day (1-31)
507 * @return the day of the week, 1=Monday .... 7=Sunday
508 */
509
510 public static int getDayOfWeek(int year, int month, int day) {
511 int d = getJulianDayNumber(year, month, day);
512 d -= 2378500; // 1800-01-05 - any Monday would do
513 while (d <= 0) {
514 d += 70000000; // any sufficiently high multiple of 7 would do
515 }
516 return (d - 1) % 7 + 1;
517 }
518
519 /**
520 * Get the ISO week number for a given date. The days of the week are numbered from
521 * 1 (Monday) to 7 (Sunday), and week 1 in any calendar year is the week (from Monday to Sunday)
522 * that includes the first Thursday of that year
523 *
524 * @param year the year
525 * @param month the month (1-12)
526 * @param day the day (1-31)
527 * @return the ISO week number
528 */
529
530 public static int getWeekNumber(int year, int month, int day) {
531 LocalDate date = LocalDate.of(year, month, day);
532 return date.get(WeekFields.ISO.weekOfWeekBasedYear());
533 }
534
535 /**
536 * Get the week number within a month. This is required for the XSLT format-date() function.
537 * The days of the week are numbered from 1 (Monday) to 7 (Sunday), and week 1
538 * in any calendar month is the week (from Monday to Sunday) that includes the first Thursday
539 * of that month.
540 * <p>See bug 21370 which clarified the specification. This caused a change to the Saxon
541 * implementation such that the days before the start of week 1 go in the last week of the previous
542 * month, not week zero.</p>
543 *
544 * @param year the year
545 * @param month the month (1-12)
546 * @param day the day (1-31)
547 * @return the week number within a month
548 */
549
550 public static int getWeekNumberWithinMonth(int year, int month, int day) {
551 int firstDay = getDayOfWeek(year, month, 1);
552 if (firstDay > 4 && (firstDay + day) <= 8) {
553 // days before week one are part of the last week of the previous month (4 or 5)
554 DateValue lastDayPrevMonth = yesterday(year, (byte) month, (byte) 1);
555 return getWeekNumberWithinMonth(lastDayPrevMonth.year, lastDayPrevMonth.month, lastDayPrevMonth.day);
556 }
557 int inc = firstDay < 5 ? 1 : 0; // implements the First Thursday rule
558 return ((day + firstDay - 2) / 7) + inc;
559 }
560
561 }
562