DateComponents.java

  1. /* Copyright 2002-2020 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.DecimalFormat;
  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 IRNSS weeks: 1999-08-22. */
  61.     public static final DateComponents IRNSS_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.     /** Serializable UID. */
  87.     private static final long serialVersionUID = -2462694707837970938L;

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

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

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

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

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

  98.     /** Format for years. */
  99.     private static final DecimalFormat FOUR_DIGITS = new DecimalFormat("0000");

  100.     /** Format for months and days. */
  101.     private static final DecimalFormat TWO_DIGITS  = new DecimalFormat("00");

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

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

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

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

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

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

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

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

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

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

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

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

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

  161.     }

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

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

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

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

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

  213.     }

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

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

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

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

  251.         return d;

  252.     }

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

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

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

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

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

  299.     }

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

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

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

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

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

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

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

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

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

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

  399.     /** Get a string representation (ISO-8601) of the date.
  400.      * @return string representation of the date.
  401.      */
  402.     public String toString() {
  403.         return new StringBuffer().
  404.                append(FOUR_DIGITS.format(year)).append('-').
  405.                append(TWO_DIGITS.format(month)).append('-').
  406.                append(TWO_DIGITS.format(day)).
  407.                toString();
  408.     }

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

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

  430.     /** {@inheritDoc} */
  431.     public int hashCode() {
  432.         return (year << 16) ^ (month << 8) ^ day;
  433.     }

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

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

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

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

  451.     }

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

  454.         /** {@inheritDoc} */
  455.         public int getYear(final int j2000Day) {
  456.             return  (int) -((-4l * j2000Day - 2920488l) / 1461l);
  457.         }

  458.         /** {@inheritDoc} */
  459.         public int getLastJ2000DayOfYear(final int year) {
  460.             return 365 * year + (year + 1) / 4 - 730123;
  461.         }

  462.         /** {@inheritDoc} */
  463.         public boolean isLeap(final int year) {
  464.             return (year % 4) == 0;
  465.         }

  466.     }

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

  469.         /** {@inheritDoc} */
  470.         public int getYear(final int j2000Day) {
  471.             return  (int) ((4l * j2000Day + 2921948l) / 1461l);
  472.         }

  473.         /** {@inheritDoc} */
  474.         public int getLastJ2000DayOfYear(final int year) {
  475.             return 365 * year + year / 4 - 730122;
  476.         }

  477.         /** {@inheritDoc} */
  478.         public boolean isLeap(final int year) {
  479.             return (year % 4) == 0;
  480.         }

  481.     }

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

  484.         /** {@inheritDoc} */
  485.         public int getYear(final int j2000Day) {

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

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

  493.             // exact year
  494.             return year;

  495.         }

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

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

  504.     }

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

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

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

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

  524.     }

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

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

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

  535.         /** {@inheritDoc} */
  536.         public int getDay(final int dayInYear, final int month) {
  537.             return dayInYear - PREVIOUS_MONTH_END_DAY[month];
  538.         }

  539.         /** {@inheritDoc} */
  540.         public int getDayInYear(final int month, final int day) {
  541.             return day + PREVIOUS_MONTH_END_DAY[month];
  542.         }

  543.     }

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

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

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

  554.         /** {@inheritDoc} */
  555.         public int getDay(final int dayInYear, final int month) {
  556.             return dayInYear - PREVIOUS_MONTH_END_DAY[month];
  557.         }

  558.         /** {@inheritDoc} */
  559.         public int getDayInYear(final int month, final int day) {
  560.             return day + PREVIOUS_MONTH_END_DAY[month];
  561.         }

  562.     }

  563. }