DateComponents.java

  1. /* Copyright 2002-2023 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.text.DecimalFormatSymbols;
  21. import java.util.Locale;
  22. import java.util.regex.Matcher;
  23. import java.util.regex.Pattern;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  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.     /** Formatting symbols used in {@link #toString()}. */
  101.     private static final DecimalFormatSymbols US_SYMBOLS = new DecimalFormatSymbols(Locale.US);

  102.     /** Format for years. */
  103.     private static final DecimalFormat FOUR_DIGITS = new DecimalFormat("0000", US_SYMBOLS);

  104.     /** Format for months and days. */
  105.     private static final DecimalFormat TWO_DIGITS  = new DecimalFormat("00", US_SYMBOLS);

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

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

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

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

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

  132.     /** Year number. */
  133.     private final int year;

  134.     /** Month number. */
  135.     private final int month;

  136.     /** Day number. */
  137.     private final int day;

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

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

  153.         // start by trusting the parameters
  154.         this.year  = year;
  155.         this.month = month;
  156.         this.day   = day;

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

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

  165.     }

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

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

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

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

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

  217.     }

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

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

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

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

  255.         return d;

  256.     }

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

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

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

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

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

  303.     }

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

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

  316.     /** Get the month as an enumerate.
  317.      * @return month as an enumerate
  318.      */
  319.     public Month getMonthEnum() {
  320.         return Month.getMonth(month);
  321.     }

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

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

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

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

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

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

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

  403.     /** Get a string representation (ISO-8601) of the date.
  404.      * @return string representation of the date.
  405.      */
  406.     public String toString() {
  407.         return new StringBuilder().
  408.                append(FOUR_DIGITS.format(year)).append('-').
  409.                append(TWO_DIGITS.format(month)).append('-').
  410.                append(TWO_DIGITS.format(day)).
  411.                toString();
  412.     }

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

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

  434.     /** {@inheritDoc} */
  435.     public int hashCode() {
  436.         return (year << 16) ^ (month << 8) ^ day;
  437.     }

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

  440.         /** Get the year number for a given day number with respect to J2000 epoch.
  441.          * @param j2000Day day number with respect to J2000 epoch
  442.          * @return year number
  443.          */
  444.         int getYear(int j2000Day);

  445.         /** Get the day number with respect to J2000 epoch for new year's Eve.
  446.          * @param year year number
  447.          * @return day number with respect to J2000 epoch for new year's Eve
  448.          */
  449.         int getLastJ2000DayOfYear(int year);

  450.         /** Check if a year is a leap or common year.
  451.          * @param year year number
  452.          * @return true if year is a leap year
  453.          */
  454.         boolean isLeap(int year);

  455.     }

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

  458.         /** {@inheritDoc} */
  459.         public int getYear(final int j2000Day) {
  460.             return  (int) -((-4l * j2000Day - 2920488l) / 1461l);
  461.         }

  462.         /** {@inheritDoc} */
  463.         public int getLastJ2000DayOfYear(final int year) {
  464.             return 365 * year + (year + 1) / 4 - 730123;
  465.         }

  466.         /** {@inheritDoc} */
  467.         public boolean isLeap(final int year) {
  468.             return (year % 4) == 0;
  469.         }

  470.     }

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

  473.         /** {@inheritDoc} */
  474.         public int getYear(final int j2000Day) {
  475.             return  (int) ((4l * j2000Day + 2921948l) / 1461l);
  476.         }

  477.         /** {@inheritDoc} */
  478.         public int getLastJ2000DayOfYear(final int year) {
  479.             return 365 * year + year / 4 - 730122;
  480.         }

  481.         /** {@inheritDoc} */
  482.         public boolean isLeap(final int year) {
  483.             return (year % 4) == 0;
  484.         }

  485.     }

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

  488.         /** {@inheritDoc} */
  489.         public int getYear(final int j2000Day) {

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

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

  497.             // exact year
  498.             return year;

  499.         }

  500.         /** {@inheritDoc} */
  501.         public int getLastJ2000DayOfYear(final int year) {
  502.             return 365 * year + year / 4 - year / 100 + year / 400 - 730120;
  503.         }

  504.         /** {@inheritDoc} */
  505.         public boolean isLeap(final int year) {
  506.             return (year % 4) == 0 && ((year % 400) == 0 || (year % 100) != 0);
  507.         }

  508.     }

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

  511.         /** Get the month number for a given day number within year.
  512.          * @param dayInYear day number within year
  513.          * @return month number
  514.          */
  515.         int getMonth(int dayInYear);

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

  522.         /** Get the day number within year for given month and day numbers.
  523.          * @param month month number
  524.          * @param day day number
  525.          * @return day number within year
  526.          */
  527.         int getDayInYear(int month, int day);

  528.     }

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

  531.         /** Months succession definition. */
  532.         private static final int[] PREVIOUS_MONTH_END_DAY = {
  533.             0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
  534.         };

  535.         /** {@inheritDoc} */
  536.         public int getMonth(final int dayInYear) {
  537.             return (dayInYear < 32) ? 1 : (10 * dayInYear + 313) / 306;
  538.         }

  539.         /** {@inheritDoc} */
  540.         public int getDay(final int dayInYear, final int month) {
  541.             return dayInYear - PREVIOUS_MONTH_END_DAY[month];
  542.         }

  543.         /** {@inheritDoc} */
  544.         public int getDayInYear(final int month, final int day) {
  545.             return day + PREVIOUS_MONTH_END_DAY[month];
  546.         }

  547.     }

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

  550.         /** Months succession definition. */
  551.         private static final int[] PREVIOUS_MONTH_END_DAY = {
  552.             0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  553.         };

  554.         /** {@inheritDoc} */
  555.         public int getMonth(final int dayInYear) {
  556.             return (dayInYear < 32) ? 1 : (10 * dayInYear + 323) / 306;
  557.         }

  558.         /** {@inheritDoc} */
  559.         public int getDay(final int dayInYear, final int month) {
  560.             return dayInYear - PREVIOUS_MONTH_END_DAY[month];
  561.         }

  562.         /** {@inheritDoc} */
  563.         public int getDayInYear(final int month, final int day) {
  564.             return day + PREVIOUS_MONTH_END_DAY[month];
  565.         }

  566.     }

  567. }