DateComponents.java

  1. /* Copyright 2002-2025 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.util.Locale;
  20. import java.util.regex.Matcher;
  21. import java.util.regex.Pattern;

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

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

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

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

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

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

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

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

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

  60.     /** Reference epoch for NavIC weeks: 1999-08-22. */
  61.     public static final DateComponents NAVIC_EPOCH;

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

  126.     /** Year number. */
  127.     private final int year;

  128.     /** Month number. */
  129.     private final int month;

  130.     /** Day number. */
  131.     private final int day;

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

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

  147.         // start by trusting the parameters
  148.         this.year  = year;
  149.         this.month = month;
  150.         this.day   = day;

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

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

  159.     }

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

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

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

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

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

  211.     }

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

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

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

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

  249.         return d;

  250.     }

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

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

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

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

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

  297.     }

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

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

  310.     /** Get the month as an enumerate.
  311.      * @return month as an enumerate
  312.      */
  313.     public Month getMonthEnum() {
  314.         return Month.getMonth(month);
  315.     }

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

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

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

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

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

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

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

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

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

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

  424.     /** {@inheritDoc} */
  425.     public int hashCode() {
  426.         return (year << 16) ^ (month << 8) ^ day;
  427.     }

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

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

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

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

  445.     }

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

  448.         /** {@inheritDoc} */
  449.         public int getYear(final int j2000Day) {
  450.             return  (int) -((-4L * j2000Day - 2920488L) / 1461L);
  451.         }

  452.         /** {@inheritDoc} */
  453.         public int getLastJ2000DayOfYear(final int year) {
  454.             return 365 * year + (year + 1) / 4 - 730123;
  455.         }

  456.         /** {@inheritDoc} */
  457.         public boolean isLeap(final int year) {
  458.             return (year % 4) == 0;
  459.         }

  460.     }

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

  463.         /** {@inheritDoc} */
  464.         public int getYear(final int j2000Day) {
  465.             return  (int) ((4L * j2000Day + 2921948L) / 1461L);
  466.         }

  467.         /** {@inheritDoc} */
  468.         public int getLastJ2000DayOfYear(final int year) {
  469.             return 365 * year + year / 4 - 730122;
  470.         }

  471.         /** {@inheritDoc} */
  472.         public boolean isLeap(final int year) {
  473.             return (year % 4) == 0;
  474.         }

  475.     }

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

  478.         /** {@inheritDoc} */
  479.         public int getYear(final int j2000Day) {

  480.             // year estimate
  481.             int year = (int) ((400L * j2000Day + 292194288L) / 146097L);

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

  487.             // exact year
  488.             return year;

  489.         }

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

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

  498.     }

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

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

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

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

  518.     }

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

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

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

  529.         /** {@inheritDoc} */
  530.         public int getDay(final int dayInYear, final int month) {
  531.             return dayInYear - PREVIOUS_MONTH_END_DAY[month];
  532.         }

  533.         /** {@inheritDoc} */
  534.         public int getDayInYear(final int month, final int day) {
  535.             return day + PREVIOUS_MONTH_END_DAY[month];
  536.         }

  537.     }

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

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

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

  548.         /** {@inheritDoc} */
  549.         public int getDay(final int dayInYear, final int month) {
  550.             return dayInYear - PREVIOUS_MONTH_END_DAY[month];
  551.         }

  552.         /** {@inheritDoc} */
  553.         public int getDayInYear(final int month, final int day) {
  554.             return day + PREVIOUS_MONTH_END_DAY[month];
  555.         }

  556.     }

  557. }