Class DateInterval

All Implemented Interfaces:
Serializable, ChronoInterval<PlainDate>

public final class DateInterval extends IsoInterval<PlainDate,​DateInterval> implements Serializable

Defines a date interval.

Since:
2.0
Author:
Meno Hochschild
See Also:
Serialized Form
  • Field Details

    • ALWAYS

      public static final DateInterval ALWAYS
      Constant for a date interval from infinite past to infinite future.
      Since:
      3.31/4.26
  • Method Details

    • comparator

      public static Comparator<ChronoInterval<PlainDate>> comparator()

      Defines a comparator which sorts intervals first by start boundary and then by length.

      Returns:
      Comparator
      Since:
      2.0
    • between

      public static DateInterval between(PlainDate start, PlainDate end)

      Creates a closed interval between given dates.

      Parameters:
      start - date of lower boundary (inclusive)
      end - date of upper boundary (inclusive)
      Returns:
      new date interval
      Throws:
      IllegalArgumentException - if start is after end
      Since:
      2.0
    • between

      public static DateInterval between(LocalDate start, LocalDate end)

      Creates a closed interval between given dates.

      Parameters:
      start - date of lower boundary (inclusive)
      end - date of upper boundary (inclusive)
      Returns:
      new date interval
      Throws:
      IllegalArgumentException - if start is after end
      Since:
      4.11
      See Also:
      between(PlainDate, PlainDate)
    • since

      public static DateInterval since(PlainDate start)

      Creates an infinite interval since given start date.

      Parameters:
      start - date of lower boundary (inclusive)
      Returns:
      new date interval
      Since:
      2.0
    • since

      public static DateInterval since(LocalDate start)

      Creates an infinite interval since given start date.

      Parameters:
      start - date of lower boundary (inclusive)
      Returns:
      new date interval
      Since:
      4.11
      See Also:
      since(PlainDate)
    • until

      public static DateInterval until(PlainDate end)

      Creates an infinite interval until given end date.

      Parameters:
      end - date of upper boundary (inclusive)
      Returns:
      new date interval
      Since:
      2.0
    • until

      public static DateInterval until(LocalDate end)

      Creates an infinite interval until given end date.

      Parameters:
      end - date of upper boundary (inclusive)
      Returns:
      new date interval
      Since:
      4.11
      See Also:
      until(PlainDate)
    • atomic

      public static DateInterval atomic(PlainDate date)

      Creates a closed interval including only given date.

      Parameters:
      date - single contained date
      Returns:
      new date interval
      Since:
      2.0
    • atomic

      public static DateInterval atomic(LocalDate date)

      Creates a closed interval including only given date.

      Parameters:
      date - single contained date
      Returns:
      new date interval
      Since:
      4.11
      See Also:
      atomic(PlainDate)
    • emptyWithAnchor

      public static DateInterval emptyWithAnchor(PlainDate anchor)

      Creates an empty interval with an anchor date.

      An empty interval does not contain any date but the anchor can modifiy the behaviour of methods like IsoInterval.meets(IsoInterval). The lower interval boundary is closed, and the upper interval boundary is open.

      Parameters:
      anchor - the anchor date
      Returns:
      new empty date interval with given anchor date
      Since:
      4.37
    • emptyWithAnchor

      public static DateInterval emptyWithAnchor(LocalDate anchor)

      Creates an empty interval with an anchor date.

      Parameters:
      anchor - the anchor date
      Returns:
      new empty date interval with given anchor date
      Since:
      4.37
      See Also:
      emptyWithAnchor(PlainDate)
    • ofCurrentWeek

      public static DateInterval ofCurrentWeek(TimeSource clock, TZID tzid, Weekday firstDay)

      Obtains the current calendar week based on given clock, time zone and first day of week.

      A localized first day of week can be obtained by the expression Weekmodel.of(Locale.getDefault()).getFirstDayOfWeek(). The next week can be found by applying move(1, CalendarUnit.DAYS) on the result of this method. If the first day of week is Monday then users should consider the alternative ISO calendar week.

      Parameters:
      clock - the clock for evaluating the current calendar week
      tzid - time zone in which the calendar week is valid
      firstDay - first day of week
      Returns:
      the current calendar week as DateInterval
      Throws:
      IllegalArgumentException - if given timezone cannot be loaded
      Since:
      5.4
      See Also:
      SystemClock.INSTANCE, Timezone.getID(), Weekmodel.getFirstDayOfWeek(), move(long, IsoDateUnit)
    • from

      public static DateInterval from(ChronoInterval<PlainDate> interval)

      Converts an arbitrary date interval to an interval of this type.

      Parameters:
      interval - any kind of date interval
      Returns:
      DateInterval
      Since:
      3.28/4.24
    • getStartAsCalendarDate

      public PlainDate getStartAsCalendarDate()

      Yields the start date.

      Returns:
      start date or null if infinite
      Since:
      4.11
      See Also:
      Boundary.isInfinite()
    • getStartAsLocalDate

      public LocalDate getStartAsLocalDate()

      Yields the start date.

      Returns:
      start date or null if infinite
      Since:
      4.11
      See Also:
      Boundary.isInfinite()
    • getEndAsCalendarDate

      public PlainDate getEndAsCalendarDate()

      Yields the end date.

      Returns:
      end date or null if infinite
      Since:
      4.11
      See Also:
      Boundary.isInfinite()
    • getEndAsLocalDate

      public LocalDate getEndAsLocalDate()

      Yields the end date.

      Returns:
      end date or null if infinite
      Since:
      4.11
      See Also:
      Boundary.isInfinite()
    • toFullDays

      public TimestampInterval toFullDays()

      Converts this instance to a timestamp interval with dates from midnight to midnight.

      The resulting interval is half-open if this interval is finite.

      Returns:
      timestamp interval (from midnight to midnight)
      Since:
      2.0
    • inTimezone

      public MomentInterval inTimezone(TZID tzid)

      Converts this instance to a moment interval with date boundaries mapped to the midnight cycle in given time zone.

      The resulting interval is half-open if this interval is finite. Note that sometimes the moments of result intervals can deviate from midnight if midnight does not exist due to daylight saving effects.

      Parameters:
      tzid - timezone identifier
      Returns:
      global timestamp intervall interpreted in given timezone
      Since:
      3.23/4.19
      See Also:
      GapResolver.NEXT_VALID_TIME, OverlapResolver.EARLIER_OFFSET
    • getLengthInDays

      public long getLengthInDays()

      Yields the length of this interval in days.

      Returns:
      duration in days as long primitive
      Throws:
      UnsupportedOperationException - if this interval is infinite
      Since:
      2.0
      See Also:
      getDurationInYearsMonthsDays(), getDuration(CalendarUnit...)
    • getDurationInYearsMonthsDays

      public Duration<CalendarUnit> getDurationInYearsMonthsDays()

      Yields the length of this interval in years, months and days.

      Returns:
      duration in years, months and days
      Throws:
      UnsupportedOperationException - if this interval is infinite
      Since:
      2.0
      See Also:
      getLengthInDays(), getDuration(CalendarUnit...)
    • getDuration

      public Duration<CalendarUnit> getDuration(CalendarUnit... units)

      Yields the length of this interval in given calendrical units.

      Parameters:
      units - calendrical units as calculation base
      Returns:
      duration in given units
      Throws:
      UnsupportedOperationException - if this interval is infinite
      Since:
      2.0
      See Also:
      getLengthInDays(), getDurationInYearsMonthsDays()
    • move

      public DateInterval move(long amount, IsoDateUnit unit)

      Moves this interval along the time axis by given units.

      Parameters:
      amount - amount of units
      unit - time unit for moving
      Returns:
      moved copy of this interval
      Since:
      3.37/4.32
    • streamDaily

      public Stream<PlainDate> streamDaily()

      Obtains a stream iterating over every calendar date of the canonical form of this interval.

      Returns:
      daily stream
      Throws:
      IllegalStateException - if this interval is infinite or if there is no canonical form
      Since:
      4.18
      See Also:
      IsoInterval.toCanonical(), streamDaily(PlainDate, PlainDate)
    • streamDaily

      public static Stream<PlainDate> streamDaily(PlainDate start, PlainDate end)

      Obtains a stream iterating over every calendar date between given interval boundaries.

      This static method avoids the costs of constructing an instance of DateInterval.

      Parameters:
      start - start boundary - inclusive
      end - end boundary - inclusive
      Returns:
      daily stream
      Throws:
      IllegalArgumentException - if start is after end
      Since:
      4.18
      See Also:
      streamDaily()
    • stream

      public Stream<PlainDate> stream(Duration<CalendarUnit> duration)

      Obtains a stream iterating over every calendar date which is the result of addition of given duration to start until the end of this interval is reached.

      Parameters:
      duration - duration which has to be added to the start multiple times
      Returns:
      stream consisting of distinct dates which are the result of adding the duration to the start
      Throws:
      IllegalArgumentException - if the duration is not positive
      IllegalStateException - if this interval is infinite or if there is no canonical form
      Since:
      4.18
      See Also:
      IsoInterval.toCanonical(), stream(Duration, PlainDate, PlainDate)
    • stream

      public static Stream<PlainDate> stream(Duration<CalendarUnit> duration, PlainDate start, PlainDate end)

      Obtains a stream iterating over every calendar date which is the result of addition of given duration to start until the end is reached.

      This static method avoids the costs of constructing an instance of DateInterval.

      Parameters:
      duration - duration which has to be added to the start multiple times
      start - start boundary - inclusive
      end - end boundary - inclusive
      Returns:
      stream consisting of distinct dates which are the result of adding the duration to the start
      Throws:
      IllegalArgumentException - if start is after end or if the duration is not positive
      Since:
      4.18
    • streamExcluding

      public Stream<PlainDate> streamExcluding(Predicate<? super PlainDate> exclusion)

      Obtains a stream iterating over every calendar date of the canonical form of this interval and applies given exclusion filter.

      Example of exclusion of Saturday and Sunday:

           DateInterval.between(
             PlainDate.of(2017, 2, 1),
             PlainDate.of(2017, 2, 8)
           ).streamExcluding(Weekday.SATURDAY.or(Weekday.SUNDAY)).forEach(System.out::println);
       

      All objects whose type is a subclass of ChronoCondition can be also used as parameter, for example localized weekends by the expression Weekmodel.of(locale).weekend().

      Parameters:
      exclusion - filter as predicate
      Returns:
      daily filtered stream
      Throws:
      IllegalStateException - if this interval is infinite or if there is no canonical form
      Since:
      4.24
      See Also:
      IsoInterval.toCanonical(), ChronoCondition
    • streamWeekBased

      public Stream<PlainDate> streamWeekBased(int weekBasedYears, int isoWeeks, int days)

      Obtains a stream iterating over every calendar date which is the result of addition of given duration in week-based units to start until the end of this interval is reached.

      Parameters:
      weekBasedYears - duration component of week-based years
      isoWeeks - duration component of calendar weeks (from Monday to Sunday)
      days - duration component of ordinary calendar days
      Returns:
      stream consisting of distinct dates which are the result of adding the duration to the start
      Throws:
      IllegalStateException - if this interval is infinite or if there is no canonical form
      IllegalArgumentException - if there is any negative duration component or if there is no positive duration component at all
      Since:
      4.18
      See Also:
      IsoInterval.toCanonical(), Weekcycle.YEARS
    • streamPartitioned

      public Stream<TimestampInterval> streamPartitioned(DayPartitionRule rule)

      Creates a partitioning stream of timestamp intervals where every day of this interval is partitioned according to given partitioning rule.

      This method enables the easy construction of daily shop opening times or weekly work time schedules.

      Parameters:
      rule - day partition rule
      Returns:
      stream of timestamp intervals
      Throws:
      IllegalStateException - if this interval is infinite or if there is no canonical form
      Since:
      4.18
      See Also:
      streamPartitioned(DayPartitionRule, TZID)
    • streamPartitioned

      public Stream<MomentInterval> streamPartitioned(DayPartitionRule rule, TZID tzid)

      Creates a partitioning stream of moment intervals where every day of this interval is partitioned according to given partitioning rule.

      This method enables the easy construction of daily shop opening times or weekly work time schedules.

      Parameters:
      rule - day partition rule
      tzid - timezone identifier
      Returns:
      stream of moment intervals
      Throws:
      IllegalStateException - if this interval is infinite or if there is no canonical form
      IllegalArgumentException - if given timezone cannot be loaded
      Since:
      4.19
      See Also:
      streamPartitioned(DayPartitionRule), GapResolver.NEXT_VALID_TIME, OverlapResolver.EARLIER_OFFSET
    • random

      public PlainDate random()

      Obtains a random date within this interval.

      Returns:
      random date within this interval
      Throws:
      IllegalStateException - if this interval is infinite or empty or if there is no canonical form
      Since:
      5.0
      See Also:
      IsoInterval.toCanonical()
    • formatISO

      public String formatISO(IsoDateStyle dateStyle, InfinityStyle infinityStyle)

      Prints the canonical form of this interval in given ISO-8601 style.

      Parameters:
      dateStyle - controlling the date format of output
      infinityStyle - controlling the format of infinite boundaries
      Returns:
      String
      Throws:
      IllegalStateException - if there is no canonical form or given infinity style prevents infinite intervals
      Since:
      4.18
      See Also:
      IsoInterval.toCanonical()
    • formatReduced

      public String formatReduced(IsoDateStyle dateStyle, InfinityStyle infinityStyle)

      Prints the canonical form of this interval in given reduced ISO-8601 style.

      The term "reduced" means that higher-order elements like the year can be left out in the end component if it is equal to the value of the start component. Example:

           DateInterval interval =
                DateInterval.between(
                    PlainDate.of(2016, 2, 29),
                    PlainDate.of(2016, 3, 13));
           System.out.println(interval.formatReduced(IsoDateStyle.EXTENDED_CALENDAR_DATE));
           // Output: 2016-02-29/03-13
       
      Parameters:
      dateStyle - controlling the date format of output
      infinityStyle - controlling the format of infinite boundaries
      Returns:
      String
      Throws:
      IllegalStateException - if there is no canonical form or given infinity style prevents infinite intervals
      Since:
      4.18
      See Also:
      IsoInterval.toCanonical()
    • parse

      public static DateInterval parse(String text, ChronoParser<PlainDate> parser) throws ParseException

      Interpretes given text as interval using a localized interval pattern.

      If given parser does not contain a reference to a locale then the interval pattern "{0}/{1}" will be used.

      Parameters:
      text - text to be parsed
      parser - format object for parsing start and end components
      Returns:
      parsed interval
      Throws:
      IndexOutOfBoundsException - if given text is empty
      ParseException - if the text is not parseable
      Since:
      3.9/4.6
      See Also:
      parse(String, ChronoParser, String), FormatPatternProvider.getIntervalPattern(Locale)
    • parse

      public static DateInterval parse(String text, ChronoParser<PlainDate> parser, String intervalPattern) throws ParseException

      Interpretes given text as interval using given interval pattern.

      Starting with version v4.18, it is also possible to use an or-pattern logic. Example:

           String multiPattern = "{0} - {1}|since {0}|until {1}";
           ChronoParser<PlainDate> parser =
                ChronoFormatter.ofDatePattern("MMMM d / uuuu", PatternType.CLDR, Locale.US);
      
           DateInterval between =
                DateInterval.parse("July 20 / 2015 - December 31 / 2015", parser, multiPattern);
           System.out.println(between); // [2015-07-20/2015-12-31]
      
           DateInterval since =
                DateInterval.parse("since July 20 / 2015", parser, multiPattern);
           System.out.println(since); // [2015-07-20/+∞)
      
           DateInterval until =
                DateInterval.parse("until December 31 / 2015", parser, multiPattern);
           System.out.println(until); // (-∞/2015-12-31]
       
      Parameters:
      text - text to be parsed
      parser - format object for parsing start and end components
      intervalPattern - interval pattern containing placeholders {0} and {1} (for start and end)
      Returns:
      parsed interval
      Throws:
      IndexOutOfBoundsException - if given text is empty
      ParseException - if the text is not parseable
      Since:
      3.9/4.6
    • parse

      public static DateInterval parse(CharSequence text, ChronoParser<PlainDate> parser, BracketPolicy policy) throws ParseException

      Interpretes given text as interval.

      This method can also accept a hyphen as alternative to solidus as separator between start and end component unless the start component is a period. Infinity symbols are understood.

      Parameters:
      text - text to be parsed
      parser - format object for parsing start and end components
      policy - strategy for parsing interval boundaries
      Returns:
      result
      Throws:
      ParseException - if parsing does not work
      IndexOutOfBoundsException - if the start position is at end of text or even behind
      Since:
      4.18
    • parse

      public static DateInterval parse(CharSequence text, ChronoParser<PlainDate> startFormat, char separator, ChronoParser<PlainDate> endFormat, BracketPolicy policy, ParseLog status)

      Interpretes given text as interval.

      This method is mainly intended for parsing technical interval formats similar to ISO-8601 which are not localized. Infinity symbols are understood.

      Parameters:
      text - text to be parsed
      startFormat - format object for parsing start component
      separator - char separating start and end component
      endFormat - format object for parsing end component
      policy - strategy for parsing interval boundaries
      status - parser information (always as new instance)
      Returns:
      result or null if parsing does not work
      Throws:
      IndexOutOfBoundsException - if the start position is at end of text or even behind
      Since:
      3.9/4.6
    • parseISO

      public static DateInterval parseISO(String text) throws ParseException

      Interpretes given ISO-conforming text as interval.

      All styles are supported, namely calendar dates, ordinal dates and week dates, either in basic or in extended format. Mixed date styles for start and end are not allowed however. Furthermore, one of start or end can also be represented by a period string. If not then the end component may exist in an abbreviated form as documented in ISO-8601-paper leaving out higher-order elements like the calendar year (which will be overtaken from the start component instead).

      The infinity symbols "-" (past and future), "-∞" (past), "+∞" (future), "-999999999-01-01" und "+999999999-12-31" can also be parsed as extension although strictly spoken ISO-8601 does not know or specify infinite intervals. Examples for supported formats:

        System.out.println(
            DateInterval.parseISO("2012-01-01/2014-06-20"));
        // output: [2012-01-01/2014-06-20]
      
        System.out.println(DateInterval.parseISO("2012-01-01/08-11"));
        // output: [2012-01-01/2012-08-11]
      
        System.out.println(DateInterval.parseISO("2012-W01-1/W06-4"));
        // output: [2012-01-02/2012-02-09]
      
        System.out.println(DateInterval.parseISO("2012-001/366"));
        // output: [2012-01-01/2012-12-31]
      
        System.out.println(DateInterval.parseISO("2012-001/+∞"));
        // output: [2012-01-01/+∞)
       

      This method dynamically creates an appropriate interval format for reduced forms. If performance is more important then a static fixed formatter might be considered.

      Parameters:
      text - text to be parsed
      Returns:
      parsed interval
      Throws:
      IndexOutOfBoundsException - if given text is empty
      ParseException - if the text is not parseable
      Since:
      2.0
      See Also:
      BracketPolicy.SHOW_NEVER