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.     /** Serializable UID. */
  88.     private static final long serialVersionUID = -2462694707837970938L;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  160.     }

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

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

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

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

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

  212.     }

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

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

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

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

  250.         return d;

  251.     }

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

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

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

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

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

  298.     }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  446.     }

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

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

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

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

  461.     }

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

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

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

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

  476.     }

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

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

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

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

  488.             // exact year
  489.             return year;

  490.         }

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

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

  499.     }

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

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

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

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

  519.     }

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

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

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

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

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

  538.     }

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

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

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

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

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

  557.     }

  558. }