Class DateTimeValue

  • All Implemented Interfaces:
    java.lang.Comparable<XPathComparable>, java.lang.Iterable<AtomicValue>, java.time.temporal.TemporalAccessor, AtomicMatchKey, XPathComparable, AtomicSequence, GroundedValue, IdentityComparable, Item, Sequence, ConversionResult

    public final class DateTimeValue
    extends CalendarValue
    implements XPathComparable, java.time.temporal.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 Detail

      • 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 Detail

      • DateTimeValue

        public DateTimeValue​(int year,
                             byte month,
                             byte day,
                             byte hour,
                             byte minute,
                             byte second,
                             int nanosecond,
                             boolean hasNoYearZero,
                             int tzMinutes,
                             AtomicType typeLabel)
      • DateTimeValue

        public DateTimeValue​(int year,
                             byte month,
                             byte day,
                             byte hour,
                             byte minute,
                             byte second,
                             int nanosecond,
                             int tz)
        Constructor: construct a DateTimeValue from its components. This constructor performs no validation.

        Note: this constructor accepts the fractional seconds value to nanosecond precision. It creates a DateTimeValue that follows XSD 1.1 conventions: that is, there is a year zero. This can be changed by setting the hasNoYearZero property.

        Parameters:
        year - The year (the year before year 1 is year 0)
        month - The month, 1-12
        day - The day 1-31
        hour - the hour value, 0-23
        minute - the minutes value, 0-59
        second - the seconds value, 0-59
        nanosecond - the number of nanoseconds, 0-999_999_999
        tz - the timezone displacement in minutes from UTC. Supply the value CalendarValue.NO_TIMEZONE if there is no timezone component.
      • DateTimeValue

        public DateTimeValue​(int year,
                             byte month,
                             byte day,
                             byte hour,
                             byte minute,
                             byte second,
                             int microsecond,
                             int tz,
                             boolean hasNoYearZero)
        Constructor: construct a DateTimeValue from its components. This constructor performs no validation.

        Note: for historic reasons, this constructor accepts the fractional seconds value only to microsecond precision. To get nanosecond precision, use the 8-argument constructor and set the XSD 1.0 option separately

        Parameters:
        year - The year as held internally (so the year before year 1 is year 0)
        month - The month, 1-12
        day - The day 1-31
        hour - the hour value, 0-23
        minute - the minutes value, 0-59
        second - the seconds value, 0-59
        microsecond - the number of microseconds, 0-999999
        tz - the timezone displacement in minutes from UTC. Supply the value CalendarValue.NO_TIMEZONE if there is no timezone component.
        hasNoYearZero - true if the dateTime value should behave under XSD 1.0 rules, that is, negative dates assume there is no year zero. Note that regardless of this setting, the year argument is set on the basis that the year before +1 is supplied as zero; but if the hasNoYearZero flag is set, this value will be displayed with a year of -1, and will return -1
    • Method Detail

      • 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​(java.util.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​(java.util.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​(java.time.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​(java.time.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​(java.time.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​(java.time.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.
      • 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
      • parse

        public static DateTimeValue parse​(UnicodeString s)
                                   throws java.time.format.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:
        java.time.format.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 byte getMonth()
        Get the month component, 1-12
        Returns:
        the month component
      • getDay

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

        public byte 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 byte getMinute()
        Get the minute component, 0-59
        Returns:
        the minute component
      • getSecond

        public byte getSecond()
        Get the second component, 0-59
        Returns:
        the second component
      • getMicrosecond

        public int getMicrosecond()
        Get the microsecond component, 0-999999
        Returns:
        the nanosecond component divided by 1000, rounded towards zero
      • getNanosecond

        public int getNanosecond()
        Get the nanosecond component, 0-999999
        Returns:
        the nanosecond 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
      • isXsd10Rules

        public boolean isXsd10Rules()
        Ask whether this value uses the XSD 1.0 rules (which don't allow year zero) or the XSD 1.1 rules (which do).
        Returns:
        true if the value uses the XSD 1.0 rules
      • 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 java.math.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​(java.math.BigDecimal instant)
        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.
      • 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 java.util.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 java.time.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 java.time.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 java.time.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 java.time.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
      • copyAsSubType

        public DateTimeValue copyAsSubType​(AtomicType typeLabel)
        Make a copy of this date, time, or dateTime value, but with a new type label
        Specified by:
        copyAsSubType in class AtomicValue
        Parameters:
        typeLabel - 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
      • secondsSinceEpoch

        public java.math.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​(java.time.temporal.TemporalField field)
        Specified by:
        isSupported in interface java.time.temporal.TemporalAccessor
      • getLong

        public long getLong​(java.time.temporal.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 java.time.temporal.TemporalAccessor
        Parameters:
        field - the field to get, not null
        Returns:
        the value for the field
        Throws:
        java.time.DateTimeException - if a value for the field cannot be obtained
        java.time.temporal.UnsupportedTemporalTypeException - if the field is not supported
        java.lang.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:
        java.lang.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)
                                           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.
        Overrides:
        getXPathComparable in class CalendarValue
        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
        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 java.lang.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:
        java.lang.ClassCastException - if the values are not comparable (which might be because no timezone is available)
      • equals

        public boolean equals​(java.lang.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,
                                          byte month,
                                          byte day,
                                          byte hour,
                                          byte minute,
                                          byte second,
                                          int nanosecond,
                                          int tzMinutes)