Class DateTimeValue

All Implemented Interfaces:
Comparable<XPathComparable>, Iterable<AtomicValue>, TemporalAccessor, AtomicMatchKey, XPathComparable, AtomicSequence, GroundedValue, IdentityComparable, Item, Sequence, ConversionResult

public final class DateTimeValue extends CalendarValue implements XPathComparable, TemporalAccessor
A value of type xs:dateTime. This contains integer fields year, month, day, hour, minute, second, and nanosecond. All these fields except year must be non-negative. In the internal representation, the sequence of years runs -2, -1, 0, +1, +2: that is, the year before year 1 is year 0.

The value also contains a boolean flag hasNoYearZero. When this flag is set, accessor methods that expose the year value subtract one if it is non-positive: that is, year 0 is displayed as -1, year -1 as -2, and so on. Constructor methods, unless otherwise specified, do not set this flag.

From Saxon 9.9, this class implements the Java 8 interface TemporalAccessor which enables it to interoperate with Java 8 temporal classes such as Instant and ZonedDateTime.

  • Field Details

    • EPOCH

      public static final DateTimeValue EPOCH
      Fixed date/time used by Java (and Unix) as the origin of the universe: 1970-01-01T00:00:00Z
  • Constructor Details

    • DateTimeValue

      public DateTimeValue(int year, int month, int day, int hour, int minute, BigDecimal seconds, int tzMinutes, AtomicMetadata typeLabel)
      Create a DateTimeValue from its components
      Parameters:
      year - the year; allows year zero
      month - the month (1 to 12)
      day - the day (1 to 31)
      hour - the hour (0 to 23)
      minute - the minute (0 to 59)
      seconds - the second ( to 59.999999...)
      tzMinutes - the timezone offset in minutes, or CalendarValue.NO_TIMEZONE if absent
      typeLabel - the type annotation
    • DateTimeValue

      public DateTimeValue(int year, int month, int day, int hour, int minute, BigDecimal seconds, int tzMinutes)
      Create a DateTimeValue from its components, defaulting the type annotation to xs:dateTimeStamp if there is a timezone, or xs:dateTime otherwise
      Parameters:
      year - the year; allows year zero
      month - the month (1 to 12)
      day - the day (1 to 31)
      hour - the hour (0 to 23)
      minute - the minute (0 to 59)
      seconds - the second ( to 59.999999...)
      tzMinutes - the timezone offset in minutes, or CalendarValue.NO_TIMEZONE if absent
  • Method Details

    • getCurrentDateTime

      public static DateTimeValue getCurrentDateTime(XPathContext context)
      Get the dateTime value representing the nominal date/time of this transformation run. Two calls within the same query or transformation will always return the same answer.
      Parameters:
      context - the XPath dynamic context. May be null, in which case the current date and time are taken directly from the system clock
      Returns:
      the current xs:dateTime
    • now

      public static DateTimeValue now()
      Get the dateTime value representing the moment of invocation of this method, in the default timezone set for the platform on which the application is running.
      Returns:
      the current dateTime, in the local timezone for the platform.
    • fromCalendar

      public static DateTimeValue fromCalendar(Calendar calendar, boolean tzSpecified)
      Constructor: create a dateTime value given a Java calendar object. The #hasNoYearZero flag is set to true.
      Parameters:
      calendar - holds the date and time
      tzSpecified - indicates whether the timezone is specified
    • fromJavaDate

      public static DateTimeValue fromJavaDate(Date suppliedDate) throws XPathException
      Factory method: create a dateTime value given a Java Date object. The returned dateTime value will always have a timezone, which will always be UTC.
      Parameters:
      suppliedDate - holds the date and time
      Returns:
      the corresponding xs:dateTime value
      Throws:
      XPathException - if a dynamic error occurs
    • fromJavaTime

      public static DateTimeValue fromJavaTime(long time) throws XPathException
      Factory method: create a dateTime value given a Java time, expressed in milliseconds since 1970. The returned dateTime value will always have a timezone, which will always be UTC.
      Parameters:
      time - the time in milliseconds since the epoch
      Returns:
      the corresponding xs:dateTime value
      Throws:
      XPathException - if a dynamic error occurs
    • fromJavaInstant

      public static DateTimeValue fromJavaInstant(long seconds, int nano) throws XPathException
      Factory method: create a dateTime value given the components of a Java Instant. The java.time.Instant class is new in JDK 8, and this method was introduced under older JDKs, so this method takes two arguments, the seconds and nano-seconds values, which can be obtained from a Java Instant using the methods getEpochSecond() and getNano() respectively
      Parameters:
      seconds - the time in seconds since the epoch
      nano - the additional nanoseconds
      Returns:
      the corresponding xs:dateTime value, which will have timezone Z (UTC)
      Throws:
      XPathException - if a dynamic error occurs (typically due to overflow)
    • fromJavaInstant

      public static DateTimeValue fromJavaInstant(Instant instant)
      Factory method: create a dateTime value given a Java Instant. The java.time.Instant class is new in JDK 8.
      Parameters:
      instant - the point in time
      Returns:
      the corresponding xs:dateTime value, which will have timezone Z (UTC)
      Since:
      9.9
    • fromZonedDateTime

      public static DateTimeValue fromZonedDateTime(ZonedDateTime zonedDateTime)
      Factory method: create a dateTime value given a Java ZonedDateTime. The java.time.ZonedDateTime class is new in JDK 8.
      Parameters:
      zonedDateTime - the supplied zonedDateTime value
      Returns:
      the corresponding xs:dateTime value, which will have the same timezone offset as the supplied ZonedDateTime; the actual (civil) timezone information is lost. The returned value will be an instance of the built-in subtype xs:dateTimeStamp
      Since:
      9.9. Changed in 10.0 to retain nanosecond precision.
    • fromOffsetDateTime

      public static DateTimeValue fromOffsetDateTime(OffsetDateTime offsetDateTime)
      Factory method: create a dateTime value given a Java OffsetDateTime. The java.time.OffsetDateTime class is new in JDK 8.
      Parameters:
      offsetDateTime - the supplied zonedDateTime value
      Returns:
      the corresponding xs:dateTime value, which will have the same timezone offset as the supplied OffsetDateTime. The returned value will be an instance of the built-in subtype xs:dateTimeStamp
      Since:
      10.0.
    • fromLocalDateTime

      public static DateTimeValue fromLocalDateTime(LocalDateTime localDateTime)
      Factory method: create a dateTime value given a Java LocalDateTime. The java.time.LocalDateTime class is new in JDK 8.
      Parameters:
      localDateTime - the supplied localDateTime value
      Returns:
      the corresponding xs:dateTime value, which will have no timezone.
      Since:
      9.9. Changed in 10.0 to retain nanosecond precision.
    • makeSeconds

      public static BigDecimal makeSeconds(int wholeSeconds, int nanoSeconds)
      Make a decimal number of seconds from the integer number of whole seconds and the integer number of nanoseconds
      Parameters:
      wholeSeconds - the number of whole seconds
      nanoSeconds - the number of nanoseconds
      Returns:
      the decimal number of seconds
    • splitSeconds

      public static int[] splitSeconds(BigDecimal seconds)
      Split a decimal number of seconds into the number of whole seconds and the number of nanoseconds
      Parameters:
      seconds - the decimal number of second
      Returns:
      an array of two integers containing first, the number of seconds, and second, the number of nanoseconds
    • formatSeconds

      public static TwineBuilder formatSeconds(BigDecimal seconds, TwineBuilder tb)
      Format a decimal seconds value
    • makeDateTimeValue

      public static DateTimeValue makeDateTimeValue(DateValue date, TimeValue time) throws XPathException
      Factory method: create a dateTime value given a date and a time.
      Parameters:
      date - the date
      time - the time
      Returns:
      the dateTime with the given components. If either component is null, returns null. The returned DateTimeValue will have the #hasNoYearZero property if and only if the supplied date has this property.
      Throws:
      XPathException - if the timezones are both present and inconsistent
    • makeDateTimeValue

      public static ConversionResult makeDateTimeValue(UnicodeString s, ConversionRules rules)
      Factory method: create a dateTime value from a supplied string, in ISO 8601 format.

      If the supplied ConversionRules object has ConversionRules.isAllowYearZero() returning true, then (a) a year value of zero is allowed in the supplied string, and (b) the hasNoYearZero property in the result is set to false. If ConversionRules.isAllowYearZero() returns false, the (a) the year value in the supplied string must not be zero, (b) a year value of -1 in the supplied string is interpreted as representing the year before year 1, and (c) the hasNoYearZero property in the result is set to true.

      Parameters:
      s - a string in the lexical space of xs:dateTime
      rules - the conversion rules to be used (determining whether year zero is allowed)
      Returns:
      either a DateTimeValue representing the xs:dateTime supplied, or a ValidationFailure if the lexical value was invalid
    • makeDateTimeValue

      public static ConversionResult makeDateTimeValue(int year, int month, int day, int hour, int minute, BigDecimal seconds, int tzMinutes)
      Creates an instance of DateTimeValue. Includes validation checks. If a validation error is detected, an instance of ValidationFailure will be returned instead.
      Parameters:
      year - - number of a year in the Gregorian calendar. Year zero is accepted.
      month - - number of a month within the specified year
      day - - number of a day within the specified month
      hour - - hour within the specified day
      minute - - minute within the hour specified
      seconds - - second within the minute specified
      tzMinutes - - number of minutes to adjust by for the timezone
      Returns:
      - an instance of DateTimeValue or ValidationFailure
    • makeDateTimeValue

      public static ConversionResult makeDateTimeValue(int year, int month, int day, int hour, int minute, BigDecimal seconds)
    • parse

      public static DateTimeValue parse(UnicodeString s) throws DateTimeParseException
      Factory method: create a dateTime value from a supplied string, in ISO 8601 format, allowing a year value of 0 to represent the year before year 1 (that is, following the XSD 1.1 rules).

      The hasNoYearZero property in the result is set to false.

      Parameters:
      s - a string in the lexical space of xs:dateTime
      Returns:
      a DateTimeValue representing the xs:dateTime supplied, including a timezone offset if present in the lexical representation
      Throws:
      DateTimeParseException - if the format of the supplied string is invalid.
      Since:
      9.9
    • getPrimitiveType

      public BuiltInAtomicType getPrimitiveType()
      Determine the primitive type of the value. This delivers the same answer as getItemType().getPrimitiveItemType(). The primitive types are the 19 primitive types of XML Schema, plus xs:integer, xs:dayTimeDuration and xs:yearMonthDuration, and xs:untypedAtomic. For external objects, the result is AnyAtomicType.
      Specified by:
      getPrimitiveType in class AtomicValue
      Returns:
      the primitive type
    • getYear

      public int getYear()
      Get the year component, in its internal form (which allows a year zero)
      Returns:
      the year component
    • getMonth

      public int getMonth()
      Get the month component, 1-12
      Returns:
      the month component
    • getDay

      public int getDay()
      Get the day component, 1-31
      Returns:
      the day component
    • getHour

      public int getHour()
      Get the hour component, 0-23
      Returns:
      the hour component (never 24, even if the input was specified as 24:00:00)
    • getMinute

      public int getMinute()
      Get the minute component, 0-59
      Returns:
      the minute component
    • getSecond

      public BigDecimal getSecond()
      Get the second component, 0-59
      Returns:
      the second component
    • toDateTime

      public DateTimeValue toDateTime()
      Convert the value to an xs:dateTime, retaining all the components that are actually present, and substituting conventional values for components that are missing. (This method does nothing in the case of xs:dateTime, but is there to implement a method in the CalendarValue interface).
      Specified by:
      toDateTime in class CalendarValue
      Returns:
      the value as an xs:dateTime
    • checkValidInJavascript

      public void checkValidInJavascript() throws XPathException
      Check that the value can be handled in SaxonJS
      Overrides:
      checkValidInJavascript in class AtomicValue
      Throws:
      XPathException - if it can't be handled in SaxonJS
    • adjustToUTC

      public DateTimeValue adjustToUTC(int implicitTimezone) throws NoDynamicContextException
      Normalize the date and time to be in timezone Z.
      Parameters:
      implicitTimezone - used to supply the implicit timezone, used when the value has no explicit timezone
      Returns:
      in general, a new DateTimeValue in timezone Z, representing the same instant in time. Returns the original DateTimeValue if this is already in timezone Z.
      Throws:
      NoDynamicContextException - if the implicit timezone is needed and is CalendarValue.MISSING_TIMEZONE or CalendarValue.NO_TIMEZONE
    • toJulianInstant

      public BigDecimal toJulianInstant()
      Get the Julian instant: a decimal value whose integer part is the Julian day number multiplied by the number of seconds per day, and whose fractional part is the fraction of the second. This method operates on the local time, ignoring the timezone. The caller should call normalize() before calling this method to get a normalized time.
      Returns:
      the Julian instant corresponding to this xs:dateTime value
    • fromJulianInstant

      public static DateTimeValue fromJulianInstant(BigDecimal instant, int tzMinutes) throws XPathException
      Get the DateTimeValue corresponding to a given Julian instant
      Parameters:
      instant - the Julian instant: a decimal value whose integer part is the Julian day number multiplied by the number of seconds per day, and whose fractional part is the fraction of the second.
      Returns:
      the xs:dateTime value corresponding to the Julian instant. This will always be in timezone Z.
      Throws:
      XPathException - if the result is out of range
    • randomSeed

      public long randomSeed()
      Generate a value from the current date and time that can be used to seed a random number generator
      Returns:
      a long derived arbitrarily from the current date and time
    • getCalendar

      public GregorianCalendar getCalendar()
      Get a Java Calendar object representing the value of this DateTime. This will respect the timezone if there is one (provided the timezone is within the range supported by the GregorianCalendar class, which in practice means that it is not -14:00). If there is no timezone or if the timezone is out of range, the result will be in GMT.
      Specified by:
      getCalendar in class CalendarValue
      Returns:
      a Java GregorianCalendar object representing the value of this xs:dateTime value.
    • toJavaInstant

      public Instant toJavaInstant()
      Get a Java 8 Instant corresponding to this date and time. The value will respect the time zone offset if present, or will assume UTC otherwise.
      Returns:
      an Instant representing this date and time
    • toZonedDateTime

      public ZonedDateTime toZonedDateTime()
      Get a Java 8 ZonedDateTime corresponding to this date and time. The value will respect the time zone offset if present, or will assume UTC otherwise.
      Returns:
      a ZonedDateTime representing this date and time, including its timezone if present, or interpreted as a UTC date/time otherwise.
      Since:
      9.9
    • toOffsetDateTime

      public OffsetDateTime toOffsetDateTime()
      Get a Java 8 OffsetDateTime corresponding to this date and time. The value will respect the time zone offset if present, or will assume UTC otherwise.
      Returns:
      a OffsetDateTime representing this date and time, including its timezone if present, or interpreted as a UTC date/time otherwise.
      Since:
      9.9
    • toLocalDateTime

      public LocalDateTime toLocalDateTime()
      Get a Java 8 LocalDateTime corresponding to this date and time. The value will ignore any timezone offset present in this value.
      Returns:
      a LocalDateTime equivalent to this date and time, discarding any time zone offset if present.
      Since:
      9.9
    • getPrimitiveStringValue

      public UnicodeString getPrimitiveStringValue()
      Convert to string
      Specified by:
      getPrimitiveStringValue in class AtomicValue
      Returns:
      ISO 8601 representation. The value returned is the localized representation: that is it uses the timezone contained within the value itself. In the case of a year earlier than year 1, the value output is the internally-held year, unless the hasNoYearZero flag is set, in which case it is the internal year minus one.
    • toDateValue

      public DateValue toDateValue()
      Extract the Date part
      Returns:
      a DateValue representing the date part of the dateTime, retaining the timezone or its absence
    • toTimeValue

      public TimeValue toTimeValue()
      Extract the Time part
      Returns:
      a TimeValue representing the date part of the dateTime, retaining the timezone or its absence
    • getCanonicalLexicalRepresentation

      public UnicodeString getCanonicalLexicalRepresentation()
      Get the canonical lexical representation as defined in XML Schema. This is not always the same as the result of casting to a string according to the XPath rules. For an xs:dateTime it is the date/time adjusted to UTC.
      Specified by:
      getCanonicalLexicalRepresentation in interface AtomicSequence
      Overrides:
      getCanonicalLexicalRepresentation in class AtomicValue
      Returns:
      the canonical lexical representation as defined in XML Schema
    • withMetadata

      public DateTimeValue withMetadata(AtomicMetadata metadata)
      Make a copy of this date, time, or dateTime value, but with a new type label
      Specified by:
      withMetadata in class AtomicValue
      Parameters:
      metadata - the type label to be attached to the new copy. It is the caller's responsibility to ensure that the value actually conforms to the rules for this type.
      Returns:
      the copied value
    • adjustTimezone

      public DateTimeValue adjustTimezone(int timezone)
      Return a new dateTime with the same normalized value, but in a different timezone.
      Specified by:
      adjustTimezone in class CalendarValue
      Parameters:
      timezone - the new timezone offset, in minutes
      Returns:
      the date/time in the new timezone. This will be a new DateTimeValue unless no change was required to the original value
    • add

      public DateTimeValue add(DurationValue duration) throws XPathException
      Add a duration to a dateTime
      Specified by:
      add in class CalendarValue
      Parameters:
      duration - the duration to be added (possibly negative)
      Returns:
      the new date
      Throws:
      XPathException - if the duration is an xs:duration, as distinct from a subclass thereof
    • subtract

      public DayTimeDurationValue subtract(CalendarValue other, XPathContext context) throws XPathException
      Determine the difference between two points in time, as a duration
      Overrides:
      subtract in class CalendarValue
      Parameters:
      other - the other point in time
      context - the XPath dynamic context
      Returns:
      the duration as an xs:dayTimeDuration
      Throws:
      XPathException - for example if one value is a date and the other is a time
    • secondsSinceEpoch

      public BigDecimal secondsSinceEpoch()
    • getComponent

      public AtomicValue getComponent(AccessorFn.Component component) throws XPathException
      Get a component of the value. Returns null if the timezone component is requested and is not present.
      Overrides:
      getComponent in class AtomicValue
      Parameters:
      component - identifies the required component
      Returns:
      the value of the requested component of this value
      Throws:
      XPathException - if a dynamic error occurs
    • isSupported

      public boolean isSupported(TemporalField field)
      Specified by:
      isSupported in interface TemporalAccessor
    • getLong

      public long getLong(TemporalField field)
      Gets the value of the specified field as a long.

      This queries the date-time for the value of the specified field. The returned value may be outside the valid range of values for the field. If the date-time cannot return the value, because the field is unsupported or for some other reason, an exception will be thrown.

      The specification requires some fields (for example ChronoField.EPOCH_DAY to reflect the local time. The Saxon implementation does not have access to the local time, so it adjusts to UTC instead.

      Specified by:
      getLong in interface TemporalAccessor
      Parameters:
      field - the field to get, not null
      Returns:
      the value for the field
      Throws:
      DateTimeException - if a value for the field cannot be obtained
      UnsupportedTemporalTypeException - if the field is not supported
      ArithmeticException - if numeric overflow occurs

      Note: Implementations must check and handle all fields defined in ChronoField. If the field is supported, then the value of the field must be returned. If unsupported, then an UnsupportedTemporalTypeException must be thrown.

      If the field is not a ChronoField, then the result of this method is obtained by invoking TemporalField.getFrom(TemporalAccessor) passing this as the argument.

      Implementations must ensure that no observable state is altered when this read-only method is invoked.

    • compareTo

      public int compareTo(CalendarValue other, int implicitTimezone) throws NoDynamicContextException
      Compare the value to another dateTime value, following the XPath comparison semantics
      Specified by:
      compareTo in class CalendarValue
      Parameters:
      other - The other dateTime value
      implicitTimezone - The implicit timezone to be used for a value with no timezone
      Returns:
      negative value if this one is the earler, 0 if they are chronologically equal, positive value if this one is the later. For this purpose, dateTime values with an unknown timezone are considered to be values in the implicit timezone (the Comparable interface requires a total ordering).
      Throws:
      ClassCastException - if the other value is not a DateTimeValue (the parameter is declared as CalendarValue to satisfy the interface)
      NoDynamicContextException - if the implicit timezone is needed and is not available
    • getXPathComparable

      public XPathComparable getXPathComparable(StringCollator collator, int implicitTimezone, int specVersion) throws NoDynamicContextException
      Description copied from class: AtomicValue
      Get an object value that implements the XPath equality and ordering comparison semantics for this value. A collation is supplied for comparing strings, and an implicit timezone for comparing date/time values that have no saved timezone. An atomic value may return itself as the result, provided that its ordering rules are independent of the collation and timezone, and provided that it implements the XPathComparable interface: which means that its compareTo, equals, and hashCode methods must be compatible with the rules for XPath value comparisons.
      Specified by:
      getXPathComparable in class AtomicValue
      Parameters:
      collator - the collation to be used when comparing strings
      implicitTimezone - the implicit timezone in the dynamic context, used when comparing dates/times with and without timezone
      specVersion - the version of the XPath specification (31 for 3.1, 40 for 4.0)
      Returns:
      an Object that implements the XPath value comparison semantics with respect to this atomic value. For an atomic type that is not ordered (according to XPath rules), return null.
      Throws:
      NoDynamicContextException - if the supplied implicit timezone is "NO_TIMEZONE" (meaning unknown), and the implicit timezone is actually required because the value in question is a date/time value with no timezone. This can cause a failure to evaluate expressions statically (because the implicit timezone is not known statically), and it will then be caught, meaning that the expression has to be evaluated dynamically.
    • compareTo

      public int compareTo(XPathComparable v2)
      Context-free comparison of two DateTimeValue values. For this to work, the two values must either both have a timezone or both have none.
      Specified by:
      compareTo in interface Comparable<XPathComparable>
      Parameters:
      v2 - the other value
      Returns:
      the result of the comparison: -1 if the first is earlier, 0 if they are equal, +1 if the first is later
      Throws:
      ClassCastException - if the values are not comparable (which might be because no timezone is available)
    • getSchemaComparable

      public DateTimeValue.DateTimeComparable getSchemaComparable()
    • equals

      public boolean equals(Object o)
      Context-free comparison of two dateTime values
      Overrides:
      equals in class AtomicValue
      Parameters:
      o - the other date time value
      Returns:
      true if the two values represent the same instant in time. Return false if one value has a timezone and the other does not (this is the result needed when using keys in a map, and also the result needed for XSD comparisons for example in enumeration facets and identity constraints)
    • hashCode

      public int hashCode()
      Hash code for context-free comparison of date time values. Note that equality testing and therefore hashCode() works only for values with a timezone
      Overrides:
      hashCode in class AtomicValue
      Returns:
      a hash code
    • computeHashCode

      public static int computeHashCode(int year, int month, int day, int hour, int minute, BigDecimal second, int tzMinutes)