DateComponents.java

  1. /* Copyright 2002-2024 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.time;

  18. import java.io.Serializable;
  19. import java.text.DecimalFormatSymbols;
  20. import java.util.Locale;
  21. import java.util.regex.Matcher;
  22. import java.util.regex.Pattern;

  23. import org.orekit.errors.OrekitIllegalArgumentException;
  24. import org.orekit.errors.OrekitMessages;

  25. /** Class representing a date broken up as year, month and day components.
  26.  * <p>This class uses the astronomical convention for calendars,
  27.  * which is also the convention used by <code>java.util.Date</code>:
  28.  * a year zero is present between years -1 and +1, and 10 days are
  29.  * missing in 1582. The calendar used around these special dates are:</p>
  30.  * <ul>
  31.  *   <li>up to 0000-12-31 : proleptic julian calendar</li>
  32.  *   <li>from 0001-01-01 to 1582-10-04: julian calendar</li>
  33.  *   <li>from 1582-10-15: gregorian calendar</li>
  34.  * </ul>
  35.  * <p>Instances of this class are guaranteed to be immutable.</p>
  36.  * @see TimeComponents
  37.  * @see DateTimeComponents
  38.  * @author Luc Maisonobe
  39.  */
  40. public class DateComponents implements Serializable, Comparable<DateComponents> {

  41.     /** Reference epoch for julian dates: -4712-01-01.
  42.      * <p>Both <code>java.util.Date</code> and {@link DateComponents} classes
  43.      * follow the astronomical conventions and consider a year 0 between
  44.      * years -1 and +1, hence this reference date lies in year -4712 and not
  45.      * in year -4713 as can be seen in other documents or programs that obey
  46.      * a different convention (for example the <code>convcal</code> utility).</p>
  47.      */
  48.     public static final DateComponents JULIAN_EPOCH;

  49.     /** Reference epoch for modified julian dates: 1858-11-17. */
  50.     public static final DateComponents MODIFIED_JULIAN_EPOCH;

  51.     /** Reference epoch for 1950 dates: 1950-01-01. */
  52.     public static final DateComponents FIFTIES_EPOCH;

  53.     /** Reference epoch for CCSDS Time Code Format (CCSDS 301.0-B-4): 1958-01-01. */
  54.     public static final DateComponents CCSDS_EPOCH;

  55.     /** Reference epoch for Galileo System Time: 1999-08-22. */
  56.     public static final DateComponents GALILEO_EPOCH;

  57.     /** Reference epoch for GPS weeks: 1980-01-06. */
  58.     public static final DateComponents GPS_EPOCH;

  59.     /** Reference epoch for QZSS weeks: 1980-01-06. */
  60.     public static final DateComponents QZSS_EPOCH;

  61.     /** Reference epoch for IRNSS weeks: 1999-08-22. */
  62.     public static final DateComponents IRNSS_EPOCH;

  63.     /** Reference epoch for BeiDou weeks: 2006-01-01. */
  64.     public static final DateComponents BEIDOU_EPOCH;

  65.     /** Reference epoch for GLONASS four-year interval number: 1996-01-01. */
  66.     public static final DateComponents GLONASS_EPOCH;

  67.     /** J2000.0 Reference epoch: 2000-01-01. */
  68.     public static final DateComponents J2000_EPOCH;

  69.     /** Java Reference epoch: 1970-01-01. */
  70.     public static final DateComponents JAVA_EPOCH;

  71.     /** Maximum supported date.
  72.      * <p>
  73.      * This is date 5881610-07-11 which corresponds to {@code Integer.MAX_VALUE}
  74.      * days after {@link #J2000_EPOCH}.
  75.      * </p>
  76.      * @since 9.0
  77.      */
  78.     public static final DateComponents MAX_EPOCH;

  79.     /** Maximum supported date.
  80.      * <p>
  81.      * This is date -5877490-03-03, which corresponds to {@code Integer.MIN_VALUE}
  82.      * days before {@link #J2000_EPOCH}.
  83.      * </p>
  84.      * @since 9.0
  85.      */
  86.     public static final DateComponents MIN_EPOCH;

  87.     /** Offset between julian day epoch and modified julian day epoch. */
  88.     public static final double JD_TO_MJD = 2400000.5;

  89.     /** Serializable UID. */
  90.     private static final long serialVersionUID = -2462694707837970938L;

  91.     /** Factory for proleptic julian calendar (up to 0000-12-31). */
  92.     private static final YearFactory PROLEPTIC_JULIAN_FACTORY = new ProlepticJulianFactory();

  93.     /** Factory for julian calendar (from 0001-01-01 to 1582-10-04). */
  94.     private static final YearFactory JULIAN_FACTORY           = new JulianFactory();

  95.     /** Factory for gregorian calendar (from 1582-10-15). */
  96.     private static final YearFactory GREGORIAN_FACTORY        = new GregorianFactory();

  97.     /** Factory for leap years. */
  98.     private static final MonthDayFactory LEAP_YEAR_FACTORY    = new LeapYearFactory();

  99.     /** Factory for non-leap years. */
  100.     private static final MonthDayFactory COMMON_YEAR_FACTORY  = new CommonYearFactory();

  101.     /** Formatting symbols used in {@link #toString()}. */
  102.     private static final DecimalFormatSymbols US_SYMBOLS = new DecimalFormatSymbols(Locale.US);

  103.     /** Offset between J2000 epoch and modified julian day epoch. */
  104.     private static final int MJD_TO_J2000 = 51544;


  105.     /** Basic and extended format calendar date. */
  106.     private static final Pattern CALENDAR_FORMAT = Pattern.compile("^(-?\\d\\d\\d\\d)-?(\\d\\d)-?(\\d\\d)$");

  107.     /** Basic and extended format ordinal date. */
  108.     private static final Pattern ORDINAL_FORMAT = Pattern.compile("^(-?\\d\\d\\d\\d)-?(\\d\\d\\d)$");

  109.     /** Basic and extended format week date. */
  110.     private static final Pattern WEEK_FORMAT = Pattern.compile("^(-?\\d\\d\\d\\d)-?W(\\d\\d)-?(\\d)$");

  111.     static {
  112.         // this static statement makes sure the reference epoch are initialized
  113.         // once AFTER the various factories have been set up
  114.         JULIAN_EPOCH          = new DateComponents(-4712,  1,  1);
  115.         MODIFIED_JULIAN_EPOCH = new DateComponents(1858, 11, 17);
  116.         FIFTIES_EPOCH         = new DateComponents(1950, 1, 1);
  117.         CCSDS_EPOCH           = new DateComponents(1958, 1, 1);
  118.         GALILEO_EPOCH         = new DateComponents(1999, 8, 22);
  119.         GPS_EPOCH             = new DateComponents(1980, 1, 6);
  120.         QZSS_EPOCH            = new DateComponents(1980, 1, 6);
  121.         IRNSS_EPOCH           = new DateComponents(1999, 8, 22);
  122.         BEIDOU_EPOCH          = new DateComponents(2006, 1, 1);
  123.         GLONASS_EPOCH         = new DateComponents(1996, 1, 1);
  124.         J2000_EPOCH           = new DateComponents(2000, 1, 1);
  125.         JAVA_EPOCH            = new DateComponents(1970, 1, 1);
  126.         MAX_EPOCH             = new DateComponents(Integer.MAX_VALUE);
  127.         MIN_EPOCH             = new DateComponents(Integer.MIN_VALUE);
  128.     }

  129.     /** Year number. */
  130.     private final int year;

  131.     /** Month number. */
  132.     private final int month;

  133.     /** Day number. */
  134.     private final int day;

  135.     /** Build a date from its components.
  136.      * @param year year number (may be 0 or negative for BC years)
  137.      * @param month month number from 1 to 12
  138.      * @param day day number from 1 to 31
  139.      * @exception IllegalArgumentException if inconsistent arguments
  140.      * are given (parameters out of range, february 29 for non-leap years,
  141.      * dates during the gregorian leap in 1582 ...)
  142.      */
  143.     public DateComponents(final int year, final int month, final int day)
  144.         throws IllegalArgumentException {

  145.         // very rough range check
  146.         // (just to avoid ArrayOutOfboundException in MonthDayFactory later)
  147.         if (month < 1 || month > 12) {
  148.             throw new OrekitIllegalArgumentException(OrekitMessages.NON_EXISTENT_MONTH, month);
  149.         }

  150.         // start by trusting the parameters
  151.         this.year  = year;
  152.         this.month = month;
  153.         this.day   = day;

  154.         // build a check date from the J2000 day
  155.         final DateComponents check = new DateComponents(getJ2000Day());

  156.         // check the parameters for mismatch
  157.         // (i.e. invalid date components, like 29 february on non-leap years)
  158.         if (year != check.year || month != check.month || day != check.day) {
  159.             throw new OrekitIllegalArgumentException(OrekitMessages.NON_EXISTENT_YEAR_MONTH_DAY,
  160.                                                       year, month, day);
  161.         }

  162.     }

  163.     /** Build a date from its components.
  164.      * @param year year number (may be 0 or negative for BC years)
  165.      * @param month month enumerate
  166.      * @param day day number from 1 to 31
  167.      * @exception IllegalArgumentException if inconsistent arguments
  168.      * are given (parameters out of range, february 29 for non-leap years,
  169.      * dates during the gregorian leap in 1582 ...)
  170.      */
  171.     public DateComponents(final int year, final Month month, final int day)
  172.         throws IllegalArgumentException {
  173.         this(year, month.getNumber(), day);
  174.     }

  175.     /** Build a date from a year and day number.
  176.      * @param year year number (may be 0 or negative for BC years)
  177.      * @param dayNumber day number in the year from 1 to 366
  178.      * @exception IllegalArgumentException if dayNumber is out of range
  179.      * with respect to year
  180.      */
  181.     public DateComponents(final int year, final int dayNumber)
  182.         throws IllegalArgumentException {
  183.         this(J2000_EPOCH, new DateComponents(year - 1, 12, 31).getJ2000Day() + dayNumber);
  184.         if (dayNumber != getDayOfYear()) {
  185.             throw new OrekitIllegalArgumentException(OrekitMessages.NON_EXISTENT_DAY_NUMBER_IN_YEAR,
  186.                                                      dayNumber, year);
  187.         }
  188.     }

  189.     /** Build a date from its offset with respect to a {@link #J2000_EPOCH}.
  190.      * @param offset offset with respect to a {@link #J2000_EPOCH}
  191.      * @see #getJ2000Day()
  192.      */
  193.     public DateComponents(final int offset) {

  194.         // we follow the astronomical convention for calendars:
  195.         // we consider a year zero and 10 days are missing in 1582
  196.         // from 1582-10-15: gregorian calendar
  197.         // from 0001-01-01 to 1582-10-04: julian calendar
  198.         // up to 0000-12-31 : proleptic julian calendar
  199.         YearFactory yFactory = GREGORIAN_FACTORY;
  200.         if (offset < -152384) {
  201.             if (offset > -730122) {
  202.                 yFactory = JULIAN_FACTORY;
  203.             } else {
  204.                 yFactory = PROLEPTIC_JULIAN_FACTORY;
  205.             }
  206.         }
  207.         year = yFactory.getYear(offset);
  208.         final int dayInYear = offset - yFactory.getLastJ2000DayOfYear(year - 1);

  209.         // handle month/day according to the year being a common or leap year
  210.         final MonthDayFactory mdFactory =
  211.             yFactory.isLeap(year) ? LEAP_YEAR_FACTORY : COMMON_YEAR_FACTORY;
  212.         month = mdFactory.getMonth(dayInYear);
  213.         day   = mdFactory.getDay(dayInYear, month);

  214.     }

  215.     /** Build a date from its offset with respect to a reference epoch.
  216.      * <p>This constructor is mainly useful to build a date from a modified
  217.      * julian day (using {@link #MODIFIED_JULIAN_EPOCH}) or a GPS week number
  218.      * (using {@link #GPS_EPOCH}).</p>
  219.      * @param epoch reference epoch
  220.      * @param offset offset with respect to a reference epoch
  221.      * @see #DateComponents(int)
  222.      * @see #getMJD()
  223.      */
  224.     public DateComponents(final DateComponents epoch, final int offset) {
  225.         this(epoch.getJ2000Day() + offset);
  226.     }

  227.     /** Build a date from week components.
  228.      * <p>The calendar week number is a number between 1 and 52 or 53 depending
  229.      * on the year. Week 1 is defined by ISO as the one that includes the first
  230.      * Thursday of a year. Week 1 may therefore start the previous year and week
  231.      * 52 or 53 may end in the next year. As an example calendar date 1995-01-01
  232.      * corresponds to week date 1994-W52-7 (i.e. Sunday in the last week of 1994
  233.      * is in fact the first day of year 1995). This date would beAnother example is calendar date
  234.      * 1996-12-31 which corresponds to week date 1997-W01-2 (i.e. Tuesday in the
  235.      * first week of 1997 is in fact the last day of year 1996).</p>
  236.      * @param wYear year associated to week numbering
  237.      * @param week week number in year, from 1 to 52 or 53
  238.      * @param dayOfWeek day of week, from 1 (Monday) to 7 (Sunday)
  239.      * @return a builded date
  240.      * @exception IllegalArgumentException if inconsistent arguments
  241.      * are given (parameters out of range, week 53 on a 52 weeks year ...)
  242.      */
  243.     public static DateComponents createFromWeekComponents(final int wYear, final int week, final int dayOfWeek)
  244.         throws IllegalArgumentException {

  245.         final DateComponents firstWeekMonday = new DateComponents(getFirstWeekMonday(wYear));
  246.         final DateComponents d = new DateComponents(firstWeekMonday, 7 * week + dayOfWeek - 8);

  247.         // check the parameters for invalid date components
  248.         if (week != d.getCalendarWeek() || dayOfWeek != d.getDayOfWeek()) {
  249.             throw new OrekitIllegalArgumentException(OrekitMessages.NON_EXISTENT_WEEK_DATE,
  250.                                                      wYear, week, dayOfWeek);
  251.         }

  252.         return d;

  253.     }

  254.     /** Parse a string in ISO-8601 format to build a date.
  255.      * <p>The supported formats are:
  256.      * <ul>
  257.      *   <li>basic format calendar date: YYYYMMDD</li>
  258.      *   <li>extended format calendar date: YYYY-MM-DD</li>
  259.      *   <li>basic format ordinal date: YYYYDDD</li>
  260.      *   <li>extended format ordinal date: YYYY-DDD</li>
  261.      *   <li>basic format week date: YYYYWwwD</li>
  262.      *   <li>extended format week date: YYYY-Www-D</li>
  263.      * </ul>
  264.      *
  265.      * <p> As shown by the list above, only the complete representations defined in section 4.1
  266.      * of ISO-8601 standard are supported, neither expended representations nor representations
  267.      * with reduced accuracy are supported.
  268.      *
  269.      * <p>
  270.      * Parsing a single integer as a julian day is <em>not</em> supported as it may be ambiguous
  271.      * with either the basic format calendar date or the basic format ordinal date depending
  272.      * on the number of digits.
  273.      * </p>
  274.      * @param string string to parse
  275.      * @return a parsed date
  276.      * @exception IllegalArgumentException if string cannot be parsed
  277.      */
  278.     public static  DateComponents parseDate(final String string) {

  279.         // is the date a calendar date ?
  280.         final Matcher calendarMatcher = CALENDAR_FORMAT.matcher(string);
  281.         if (calendarMatcher.matches()) {
  282.             return new DateComponents(Integer.parseInt(calendarMatcher.group(1)),
  283.                                       Integer.parseInt(calendarMatcher.group(2)),
  284.                                       Integer.parseInt(calendarMatcher.group(3)));
  285.         }

  286.         // is the date an ordinal date ?
  287.         final Matcher ordinalMatcher = ORDINAL_FORMAT.matcher(string);
  288.         if (ordinalMatcher.matches()) {
  289.             return new DateComponents(Integer.parseInt(ordinalMatcher.group(1)),
  290.                                       Integer.parseInt(ordinalMatcher.group(2)));
  291.         }

  292.         // is the date a week date ?
  293.         final Matcher weekMatcher = WEEK_FORMAT.matcher(string);
  294.         if (weekMatcher.matches()) {
  295.             return createFromWeekComponents(Integer.parseInt(weekMatcher.group(1)),
  296.                                             Integer.parseInt(weekMatcher.group(2)),
  297.                                             Integer.parseInt(weekMatcher.group(3)));
  298.         }

  299.         throw new OrekitIllegalArgumentException(OrekitMessages.NON_EXISTENT_DATE, string);

  300.     }

  301.     /** Get the year number.
  302.      * @return year number (may be 0 or negative for BC years)
  303.      */
  304.     public int getYear() {
  305.         return year;
  306.     }

  307.     /** Get the month.
  308.      * @return month number from 1 to 12
  309.      */
  310.     public int getMonth() {
  311.         return month;
  312.     }

  313.     /** Get the month as an enumerate.
  314.      * @return month as an enumerate
  315.      */
  316.     public Month getMonthEnum() {
  317.         return Month.getMonth(month);
  318.     }

  319.     /** Get the day.
  320.      * @return day number from 1 to 31
  321.      */
  322.     public int getDay() {
  323.         return day;
  324.     }

  325.     /** Get the day number with respect to J2000 epoch.
  326.      * @return day number with respect to J2000 epoch
  327.      */
  328.     public int getJ2000Day() {
  329.         YearFactory yFactory = GREGORIAN_FACTORY;
  330.         if (year < 1583) {
  331.             if (year < 1) {
  332.                 yFactory = PROLEPTIC_JULIAN_FACTORY;
  333.             } else if (year < 1582 || month < 10 || month < 11 && day < 5) {
  334.                 yFactory = JULIAN_FACTORY;
  335.             }
  336.         }
  337.         final MonthDayFactory mdFactory =
  338.             yFactory.isLeap(year) ? LEAP_YEAR_FACTORY : COMMON_YEAR_FACTORY;
  339.         return yFactory.getLastJ2000DayOfYear(year - 1) +
  340.                mdFactory.getDayInYear(month, day);
  341.     }

  342.     /** Get the modified julian day.
  343.      * @return modified julian day
  344.      */
  345.     public int getMJD() {
  346.         return MJD_TO_J2000 + getJ2000Day();
  347.     }

  348.     /** Get the calendar week number.
  349.      * <p>The calendar week number is a number between 1 and 52 or 53 depending
  350.      * on the year. Week 1 is defined by ISO as the one that includes the first
  351.      * Thursday of a year. Week 1 may therefore start the previous year and week
  352.      * 52 or 53 may end in the next year. As an example calendar date 1995-01-01
  353.      * corresponds to week date 1994-W52-7 (i.e. Sunday in the last week of 1994
  354.      * is in fact the first day of year 1995). Another example is calendar date
  355.      * 1996-12-31 which corresponds to week date 1997-W01-2 (i.e. Tuesday in the
  356.      * first week of 1997 is in fact the last day of year 1996).</p>
  357.      * @return calendar week number
  358.      */
  359.     public int getCalendarWeek() {
  360.         final int firstWeekMonday = getFirstWeekMonday(year);
  361.         int daysSincefirstMonday = getJ2000Day() - firstWeekMonday;
  362.         if (daysSincefirstMonday < 0) {
  363.             // we are still in a week from previous year
  364.             daysSincefirstMonday += firstWeekMonday - getFirstWeekMonday(year - 1);
  365.         } else if (daysSincefirstMonday > 363) {
  366.             // up to three days at end of year may belong to first week of next year
  367.             // (by chance, there is no need for a specific check in year 1582 ...)
  368.             final int weekYearLength = getFirstWeekMonday(year + 1) - firstWeekMonday;
  369.             if (daysSincefirstMonday >= weekYearLength) {
  370.                 daysSincefirstMonday -= weekYearLength;
  371.             }
  372.         }
  373.         return 1 + daysSincefirstMonday / 7;
  374.     }

  375.     /** Get the monday of a year first week.
  376.      * @param year year to consider
  377.      * @return day of the monday of the first weak of year
  378.      */
  379.     private static int getFirstWeekMonday(final int year) {
  380.         final int yearFirst = new DateComponents(year, 1, 1).getJ2000Day();
  381.         final int offsetToMonday = 4 - (yearFirst + 2) % 7;
  382.         return yearFirst + offsetToMonday + ((offsetToMonday > 3) ? -7 : 0);
  383.     }

  384.     /** Get the day of week.
  385.      * <p>Day of week is a number between 1 (Monday) and 7 (Sunday).</p>
  386.      * @return day of week
  387.      */
  388.     public int getDayOfWeek() {
  389.         final int dow = (getJ2000Day() + 6) % 7; // result is between -6 and +6
  390.         return (dow < 1) ? (dow + 7) : dow;
  391.     }

  392.     /** Get the day number in year.
  393.      * <p>Day number in year is between 1 (January 1st) and either 365 or
  394.      * 366 inclusive depending on year.</p>
  395.      * @return day number in year
  396.      */
  397.     public int getDayOfYear() {
  398.         return getJ2000Day() - new DateComponents(year - 1, 12, 31).getJ2000Day();
  399.     }

  400.     /** Get a string representation (ISO-8601) of the date.
  401.      * @return string representation of the date.
  402.      */
  403.     public String toString() {
  404.         return String.format(Locale.US, "%04d-%02d-%02d", year, month, day);
  405.     }

  406.     /** {@inheritDoc} */
  407.     public int compareTo(final DateComponents other) {
  408.         final int j2000Day = getJ2000Day();
  409.         final int otherJ2000Day = other.getJ2000Day();
  410.         if (j2000Day < otherJ2000Day) {
  411.             return -1;
  412.         } else if (j2000Day > otherJ2000Day) {
  413.             return 1;
  414.         }
  415.         return 0;
  416.     }

  417.     /** {@inheritDoc} */
  418.     public boolean equals(final Object other) {
  419.         try {
  420.             final DateComponents otherDate = (DateComponents) other;
  421.             return otherDate != null && year == otherDate.year &&
  422.                    month == otherDate.month && day == otherDate.day;
  423.         } catch (ClassCastException cce) {
  424.             return false;
  425.         }
  426.     }

  427.     /** {@inheritDoc} */
  428.     public int hashCode() {
  429.         return (year << 16) ^ (month << 8) ^ day;
  430.     }

  431.     /** Interface for dealing with years sequences according to some calendar. */
  432.     private interface YearFactory {

  433.         /** Get the year number for a given day number with respect to J2000 epoch.
  434.          * @param j2000Day day number with respect to J2000 epoch
  435.          * @return year number
  436.          */
  437.         int getYear(int j2000Day);

  438.         /** Get the day number with respect to J2000 epoch for new year's Eve.
  439.          * @param year year number
  440.          * @return day number with respect to J2000 epoch for new year's Eve
  441.          */
  442.         int getLastJ2000DayOfYear(int year);

  443.         /** Check if a year is a leap or common year.
  444.          * @param year year number
  445.          * @return true if year is a leap year
  446.          */
  447.         boolean isLeap(int year);

  448.     }

  449.     /** Class providing a years sequence compliant with the proleptic Julian calendar. */
  450.     private static class ProlepticJulianFactory implements YearFactory {

  451.         /** {@inheritDoc} */
  452.         public int getYear(final int j2000Day) {
  453.             return  (int) -((-4l * j2000Day - 2920488l) / 1461l);
  454.         }

  455.         /** {@inheritDoc} */
  456.         public int getLastJ2000DayOfYear(final int year) {
  457.             return 365 * year + (year + 1) / 4 - 730123;
  458.         }

  459.         /** {@inheritDoc} */
  460.         public boolean isLeap(final int year) {
  461.             return (year % 4) == 0;
  462.         }

  463.     }

  464.     /** Class providing a years sequence compliant with the Julian calendar. */
  465.     private static class JulianFactory implements YearFactory {

  466.         /** {@inheritDoc} */
  467.         public int getYear(final int j2000Day) {
  468.             return  (int) ((4l * j2000Day + 2921948l) / 1461l);
  469.         }

  470.         /** {@inheritDoc} */
  471.         public int getLastJ2000DayOfYear(final int year) {
  472.             return 365 * year + year / 4 - 730122;
  473.         }

  474.         /** {@inheritDoc} */
  475.         public boolean isLeap(final int year) {
  476.             return (year % 4) == 0;
  477.         }

  478.     }

  479.     /** Class providing a years sequence compliant with the Gregorian calendar. */
  480.     private static class GregorianFactory implements YearFactory {

  481.         /** {@inheritDoc} */
  482.         public int getYear(final int j2000Day) {

  483.             // year estimate
  484.             int year = (int) ((400l * j2000Day + 292194288l) / 146097l);

  485.             // the previous estimate is one unit too high in some rare cases
  486.             // (240 days in the 400 years gregorian cycle, about 0.16%)
  487.             if (j2000Day <= getLastJ2000DayOfYear(year - 1)) {
  488.                 --year;
  489.             }

  490.             // exact year
  491.             return year;

  492.         }

  493.         /** {@inheritDoc} */
  494.         public int getLastJ2000DayOfYear(final int year) {
  495.             return 365 * year + year / 4 - year / 100 + year / 400 - 730120;
  496.         }

  497.         /** {@inheritDoc} */
  498.         public boolean isLeap(final int year) {
  499.             return (year % 4) == 0 && ((year % 400) == 0 || (year % 100) != 0);
  500.         }

  501.     }

  502.     /** Interface for dealing with months sequences according to leap/common years. */
  503.     private interface MonthDayFactory {

  504.         /** Get the month number for a given day number within year.
  505.          * @param dayInYear day number within year
  506.          * @return month number
  507.          */
  508.         int getMonth(int dayInYear);

  509.         /** Get the day number for given month and day number within year.
  510.          * @param dayInYear day number within year
  511.          * @param month month number
  512.          * @return day number
  513.          */
  514.         int getDay(int dayInYear, int month);

  515.         /** Get the day number within year for given month and day numbers.
  516.          * @param month month number
  517.          * @param day day number
  518.          * @return day number within year
  519.          */
  520.         int getDayInYear(int month, int day);

  521.     }

  522.     /** Class providing the months sequence for leap years. */
  523.     private static class LeapYearFactory implements MonthDayFactory {

  524.         /** Months succession definition. */
  525.         private static final int[] PREVIOUS_MONTH_END_DAY = {
  526.             0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
  527.         };

  528.         /** {@inheritDoc} */
  529.         public int getMonth(final int dayInYear) {
  530.             return (dayInYear < 32) ? 1 : (10 * dayInYear + 313) / 306;
  531.         }

  532.         /** {@inheritDoc} */
  533.         public int getDay(final int dayInYear, final int month) {
  534.             return dayInYear - PREVIOUS_MONTH_END_DAY[month];
  535.         }

  536.         /** {@inheritDoc} */
  537.         public int getDayInYear(final int month, final int day) {
  538.             return day + PREVIOUS_MONTH_END_DAY[month];
  539.         }

  540.     }

  541.     /** Class providing the months sequence for common years. */
  542.     private static class CommonYearFactory implements MonthDayFactory {

  543.         /** Months succession definition. */
  544.         private static final int[] PREVIOUS_MONTH_END_DAY = {
  545.             0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  546.         };

  547.         /** {@inheritDoc} */
  548.         public int getMonth(final int dayInYear) {
  549.             return (dayInYear < 32) ? 1 : (10 * dayInYear + 323) / 306;
  550.         }

  551.         /** {@inheritDoc} */
  552.         public int getDay(final int dayInYear, final int month) {
  553.             return dayInYear - PREVIOUS_MONTH_END_DAY[month];
  554.         }

  555.         /** {@inheritDoc} */
  556.         public int getDayInYear(final int month, final int day) {
  557.             return day + PREVIOUS_MONTH_END_DAY[month];
  558.         }

  559.     }

  560. }