001/*
002 * Zmanim Java API
003 * Copyright © 2011 - 2026 Eliyahu Hershfeld
004 * Copyright © September 2002 Avrom Finkelstein
005 * Copyright © 2026 Moshe Dicker
006 *
007 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General
008 * Public License as published by the Free Software Foundation; version 2.1 of the License.
009 *
010 * This library is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied
011 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012 * details.
013 * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to
014 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA,
015 * or connect to: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
016 */
017package com.kosherjava.zmanim.hebrewcalendar;
018
019import java.time.LocalDate;
020import java.time.YearMonth;
021import java.time.ZonedDateTime;
022
023/**
024 * The JewishDate is the base calendar class, that supports maintenance of a {@link LocalDate}
025 * instance along with the corresponding Jewish date. This class can use the standard Java Date and Calendar
026 * classes for setting and maintaining the dates, but it does not subclass these classes or use them internally
027 * in any calculations. This class also does not have a concept of a time (which the Date class does). Please
028 * note that the calendar does not currently support dates prior to 1/1/1 Gregorian. Also keep in mind that the
029 * Gregorian calendar started on October 15, 1582, so any calculations prior to that are suspect (at least from
030 * a Gregorian perspective). While 1/1/1 Gregorian and forward are technically supported, any calculations prior to <a
031 * href="http://en.wikipedia.org/wiki/Hillel_II">Hillel II's (Hakatan's</a>) calendar (4119 in the Jewish Calendar / 359
032 * CE Julian as recorded by <a href="http://en.wikipedia.org/wiki/Hai_Gaon">Rav Hai Gaon</a>) would be just an
033 * approximation.
034 *
035 * This open source Java code was written by <a href="https://www.linkedin.com/in/avromf/">Avrom Finkelstein</a> from his C++
036 * code. It was refactored to fit the KosherJava Zmanim API with simplification of the code, enhancements and some bug
037 * fixing.
038 *
039 * Some of Avrom's original C++ code was translated from
040 * <a href="https://web.archive.org/web/20120124134148/http://emr.cs.uiuc.edu/~reingold/calendar.C">C/C++ code</a> in
041 * <a href="http://www.calendarists.com">Calendrical Calculations</a> by Nachum Dershowitz and Edward M.
042 * Reingold, Software-- Practice &amp; Experience, vol. 20, no. 9 (September, 1990), pp. 899- 928. Any method with the mark
043 * "ND+ER" indicates that the method was taken from this source with minor modifications.
044 *
045 * If you are looking for a class that implements a Jewish calendar version of the Calendar class, one is available from
046 * the <a href="http://site.icu-project.org/" >ICU (International Components for Unicode)</a> project, formerly part of
047 * IBM's DeveloperWorks.
048 *
049 * @see JewishCalendar
050 * @see HebrewDateFormatter
051 * @see java.util.Date
052 * @see java.util.Calendar
053 * @author © Avrom Finkelstein 2002
054 * @author © Moshe Dicker 2026
055 * @author © Eliyahu Hershfeld 2011 - 2026
056 */
057public class JewishDate implements Comparable<JewishDate>, Cloneable {
058        /**
059         * Value of the month field indicating Nissan, the first numeric month of the year in the Jewish calendar. With the year
060         * starting at {@link #TISHREI}, it would actually be the 7th (or 8th in a {@link #isJewishLeapYear() leap year}) month of
061         * the year.
062         */
063        public static final int NISSAN = 1;
064
065        /**
066         * Value of the month field indicating Iyar, the second numeric month of the year in the Jewish calendar. With the year starting
067         * at {@link #TISHREI}, it would actually be the 8th (or 9th in a {@link #isJewishLeapYear() leap year}) month of the year.
068         */
069        public static final int IYAR = 2;
070
071        /**
072         * Value of the month field indicating Sivan, the third numeric month of the year in the Jewish calendar. With the year starting
073         * at {@link #TISHREI}, it would actually be the 9th (or 10th in a {@link #isJewishLeapYear() leap year}) month of the year.
074         */
075        public static final int SIVAN = 3;
076
077        /**
078         * Value of the month field indicating Tammuz, the fourth numeric month of the year in the Jewish calendar. With the year
079         * starting at {@link #TISHREI}, it would actually be the 10th (or 11th in a {@link #isJewishLeapYear() leap year}) month of the
080         * year.
081         */
082        public static final int TAMMUZ = 4;
083
084        /**
085         * Value of the month field indicating Av, the fifth numeric month of the year in the Jewish calendar. With the year starting at
086         * {@link #TISHREI}, it would actually be the 11th (or 12th in a {@link #isJewishLeapYear() leap year}) month of the year.
087         */
088        public static final int AV = 5;
089
090        /**
091         * Value of the month field indicating Elul, the sixth numeric month of the year in the Jewish calendar. With the year starting
092         * at {@link #TISHREI}, it would actually be the 12th (or 13th in a {@link #isJewishLeapYear() leap year}) month of the year.
093         */
094        public static final int ELUL = 6;
095
096        /**
097         * Value of the month field indicating Tishrei, the seventh numeric month of the year in the Jewish calendar. With the year
098         * starting at this month, it would actually be the 1st month of the year.
099         */
100        public static final int TISHREI = 7;
101
102        /**
103         * Value of the month field indicating Cheshvan/marcheshvan, the eighth numeric month of the year in the Jewish calendar. With
104         * the year starting at {@link #TISHREI}, it would actually be the 2nd month of the year.
105         */
106        public static final int CHESHVAN = 8;
107
108        /**
109         * Value of the month field indicating Kislev, the ninth numeric month of the year in the Jewish calendar. With the year starting
110         * at {@link #TISHREI}, it would actually be the 3rd month of the year.
111         */
112        public static final int KISLEV = 9;
113
114        /**
115         * Value of the month field indicating Teves, the tenth numeric month of the year in the Jewish calendar. With the
116         * year starting at {@link #TISHREI}, it would actually be the 4th month of the year.
117         */
118        public static final int TEVES = 10;
119
120        /**
121         * Value of the month field indicating Shevat, the eleventh numeric month of the year in the Jewish calendar. With
122         * the year starting at {@link #TISHREI}, it would actually be the 5th month of the year.
123         */
124        public static final int SHEVAT = 11;
125
126        /**
127         * Value of the month field indicating Adar (or Adar I in a {@link #isJewishLeapYear() leap year}), the twelfth
128         * numeric month of the year in the Jewish calendar. With the year starting at {@link #TISHREI}, it would actually
129         * be the 6th month of the year.
130         */
131        public static final int ADAR = 12;
132
133        /**
134         * Value of the month field indicating Adar II, the leap (intercalary or embolismic) thirteenth (Undecimber) numeric
135         * month of the year added in Jewish {@link #isJewishLeapYear() leap year}). The leap years are years 3, 6, 8, 11,
136         * 14, 17 and 19 of a 19-year cycle. With the year starting at {@link #TISHREI}, it would actually be the 7th month
137         * of the year.
138         */
139        public static final int ADAR_II = 13;
140
141        /**
142         * the Jewish epoch using the RD (Rata Die/Fixed Date or Reingold Dershowitz) day used in Calendrical Calculations.
143         * Day 1 is January 1, 0001 of the Gregorian calendar
144         */
145        private static final int JEWISH_EPOCH = -1373429;
146
147        /** The number  of <em>chalakim</em> (18) in a minute.*/
148        private static final int CHALAKIM_PER_MINUTE = 18;
149        /** The number  of <em>chalakim</em> (1080) in an hour.*/
150        private static final int CHALAKIM_PER_HOUR = 1080;
151        /** The number of <em>chalakim</em> (25,920) in a 24-hour day .*/
152        private static final long CHALAKIM_PER_DAY = 25920; // 24 * 1080
153        /** The number  of <em>chalakim</em> in an average Jewish month. A month has 29 days, 12 hours and 793
154         * <em>chalakim</em> (44 minutes and 3.3 seconds) for a total of 765,433 <em>chalakim</em>*/
155        private static final long CHALAKIM_PER_MONTH = 765433; // (29 * 24 + 12) * 1080 + 793
156        /**
157         * Days from the beginning of Sunday till <em>molad BaHaRaD</em>. Calculated as 1 day, 5 hours and 204 <em>chalakim</em> =
158         * (24 + 5) * 1080 + 204 = 31524
159         */
160        private static final int CHALAKIM_MOLAD_TOHU = 31524;
161
162        /**
163         * A short year where both {@link #CHESHVAN} and {@link #KISLEV} are 29 days.
164         *
165         * @see #getCheshvanKislevKviah()
166         * @see HebrewDateFormatter#getFormattedKviah(int)
167         */
168        public static final int CHASERIM = 0;
169
170        /**
171         * An ordered year where {@link #CHESHVAN} is 29 days and {@link #KISLEV} is 30 days.
172         *
173         * @see #getCheshvanKislevKviah()
174         * @see HebrewDateFormatter#getFormattedKviah(int)
175         */
176        public static final int KESIDRAN = 1;
177
178        /**
179         * A long year where both {@link #CHESHVAN} and {@link #KISLEV} are 30 days.
180         *
181         * @see #getCheshvanKislevKviah()
182         * @see HebrewDateFormatter#getFormattedKviah(int)
183         */
184        public static final int SHELAIMIM = 2;
185
186        /** the internal Jewish month.*/
187        private int jewishMonth;
188        /** the internal Jewish day.*/
189        private int jewishDay;
190        /** the internal Jewish year.*/
191        private int jewishYear;
192        /** the internal count of <em>molad</em> hours.*/
193        private int moladHours;
194        /** the internal count of <em>molad</em> minutes.*/
195        private int moladMinutes;
196        /** the internal count of <em>molad chalakim</em>.*/
197        private int moladChalakim;
198
199        /**
200         * Returns the <em>molad</em> hours. Only a JewishDate object populated with {@link #getMolad()},
201         * {@link #setJewishDate(int, int, int, int, int, int)} or {@link #setMoladHours(int)} will have this field
202         * populated. A regular JewishDate object will have this field set to 0.
203         *
204         * @return the <em>molad</em> hours
205         * @see #setMoladHours(int)
206         * @see #getMolad()
207         * @see #setJewishDate(int, int, int, int, int, int)
208         */
209        public int getMoladHours() {
210                return moladHours;
211        }
212
213        /**
214         * Sets the <em>molad</em> hours.
215         *
216         * @param moladHours the <em>molad</em> hours to set
217         * @see #getMoladHours()
218         * @see #getMolad()
219         * @see #setJewishDate(int, int, int, int, int, int)
220         *
221         */
222        public void setMoladHours(int moladHours) {
223                this.moladHours = moladHours;
224        }
225
226        /**
227         * Returns the <em>molad</em> minutes. Only an object populated with {@link #getMolad()},
228         * {@link #setJewishDate(int, int, int, int, int, int)} or {@link #setMoladMinutes(int)} will have these fields populated.
229         * A regular JewishDate object will have this field set to 0.
230         *
231         * @return the <em>molad</em> minutes
232         * @see #setMoladMinutes(int)
233         * @see #getMolad()
234         * @see #setJewishDate(int, int, int, int, int, int)
235         */
236        public int getMoladMinutes() {
237                return moladMinutes;
238        }
239
240        /**
241         * Sets the <em>molad</em> minutes. The expectation is that the traditional minute-less <em>chalakim</em> will be broken out to
242         * minutes and {@link #setMoladChalakim(int) <em>chalakim</em> / parts} , so 793 (TaShTZaG) parts would have the minutes set to
243         * 44 and <em>chalakim</em> to 1.
244         *
245         * @param moladMinutes the molad minutes to set
246         * @see #getMoladMinutes()
247         * @see #setMoladChalakim(int)
248         * @see #getMolad()
249         * @see #setJewishDate(int, int, int, int, int, int)
250         *
251         */
252        public void setMoladMinutes(int moladMinutes) {
253                this.moladMinutes = moladMinutes;
254        }
255
256        /**
257         * Sets the <em>molad</em> chalakim/parts. The expectation is that the traditional minute-less <em>chalakim</em> will be broken
258         * out to {@link #setMoladMinutes(int) minutes} and chalakim, so 793 (TaShTZaG) parts would have the minutes set to 44 and
259         * <em>chalakim</em> to 1.
260         *
261         * @param moladChalakim the <em>molad chalakim</em> / parts to set
262         * @see #getMoladChalakim()
263         * @see #setMoladMinutes(int)
264         * @see #getMolad()
265         * @see #setJewishDate(int, int, int, int, int, int)
266         *
267         */
268        public void setMoladChalakim(int moladChalakim) {
269                this.moladChalakim = moladChalakim;
270        }
271
272        /**
273         * Returns the <em>molad chalakim</em> / parts. Only an object populated with {@link #getMolad()},
274         * {@link #setJewishDate(int, int, int, int, int, int)} or {@link #setMoladChalakim(int)} will have these fields
275         * populated. A regular JewishDate object will have this field set to 0.
276         *
277         * @return the <em>molad chalakim</em> / parts
278         * @see #setMoladChalakim(int)
279         * @see #getMolad()
280         * @see #setJewishDate(int, int, int, int, int, int)
281         */
282        public int getMoladChalakim() {
283                return moladChalakim;
284        }
285
286        /** 1 == Sunday, 2 == Monday, etc... */
287        private int dayOfWeek;
288
289        /** Returns the absolute date (days since January 1, 0001 of the Gregorian calendar).
290         * @see #getAbsDate()
291         * @see #setAbsDate(int)
292         */
293        private int gregorianAbsDate;
294
295        /**
296         * Returns the number of days in a given month in a given year and month.
297         *
298         * @param year the year (only impacts February)
299         * @param month the month. As with other cases in this class, this is 1-based, not zero-based.
300         * @return the number of days in the month in the given year
301         */
302        private static int getLastDayOfGregorianMonth(int year, int month) {
303                return YearMonth.of(year, month).lengthOfMonth();
304        }
305
306        /**
307         * Computes the Gregorian date from the absolute date. ND+ER
308         * @param absDate the absolute date
309         * @return the {@code LocalDate}.
310         */
311        private static LocalDate absDateToDate(int absDate) {
312                int year = Math.floorDiv(absDate, 366); // Search forward year by year from approximate year
313                while (absDate >= gregorianDateToAbsDate(year + 1, 1, 1)) {
314                        year++;
315                }
316
317                int month = 1; // Search forward month by month from January
318                while (absDate > gregorianDateToAbsDate(year, month, getLastDayOfGregorianMonth(year, month))) {
319                        month++;
320                }
321
322                int dayOfMonth = absDate - gregorianDateToAbsDate(year, month, 1) + 1;
323                return LocalDate.of(year, month, dayOfMonth);
324        }
325
326        /**
327         * Returns the absolute date (days since January 1, 0001 of the Gregorian calendar).
328         *
329         * @return the number of days since January 1, 1
330         */
331        public int getAbsDate() {
332                return gregorianAbsDate;
333        }
334
335        /**
336         * Computes the absolute date from a Gregorian date. ND+ER
337         *
338         * @param year the Gregorian year
339         * @param month the Gregorian month. Unlike the Java Calendar where January has the value of 0,This expects a 1 for January
340         * @param dayOfMonth the day of the month (1st, 2nd, etc...)
341     * @return the absolute Gregorian day
342     */
343    private static int gregorianDateToAbsDate(int year, int month, int dayOfMonth) {
344        int absDate = dayOfMonth;
345        for (int m = month - 1; m > 0; m--) {
346            absDate += getLastDayOfGregorianMonth(year, m); // days in prior months of the year
347        }
348
349        int y = year - 1;
350        // Floor division, so that year 0, a leap year, gets its leap day
351                return (absDate // days this year
352                                + 365 * y // days in previous years ignoring leap days
353                + Math.floorDiv(y, 4) // Julian leap days before this year
354                - Math.floorDiv(y, 100) // minus prior century years
355                + Math.floorDiv(y, 400)); // plus prior years divisible by 400
356    }
357
358    /**
359     * Returns if the year is a Jewish leap year. Years 3, 6, 8, 11, 14, 17 and 19 in the 19-year cycle are leap years.
360     *
361     * @param year the Jewish year.
362     * @return true if it is a leap year
363     * @see #isJewishLeapYear()
364     */
365    public static boolean isJewishLeapYear(int year) {
366        return ((7 * year) + 1) % 19 < 7;
367    }
368
369    /**
370     * Returns if the year the calendar is set to is a Jewish leap year. Years 3, 6, 8, 11, 14, 17 and 19 in the 19-year
371     * cycle are leap years.
372     *
373     * @return true if it is a leap year
374     * @see #isJewishLeapYear(int)
375     */
376    public boolean isJewishLeapYear() {
377        return isJewishLeapYear(getJewishYear());
378    }
379
380    /**
381     * Returns the last month of a given Jewish year. This will be 12 on a non {@link #isJewishLeapYear(int) leap year}
382     * or 13 on a leap year.
383     *
384     * @param year the Jewish year.
385     * @return 12 on a non leap year or 13 on a leap year
386     * @see #isJewishLeapYear(int)
387     */
388    private static int getLastMonthOfJewishYear(int year) {
389        return isJewishLeapYear(year) ? ADAR_II : ADAR;
390    }
391
392    /**
393     * Returns the number of days elapsed from the Sunday prior to the start of the Jewish calendar to the mean
394     * conjunction of Tishri of the Jewish year.
395     *
396     * @param year the Jewish year
397     * @return the number of days elapsed from prior to the <em>molad Tohu BaHaRaD</em> (Be = Monday, <em>Ha</em> = 5
398     *         hours and <em>RaD</em> = 204 <em>chalakim</em> / parts) prior to the start of the Jewish calendar, to
399     *         the mean conjunction of Tishri of the Jewish year. BeHaRaD is 23:11:20 on Sunday night(5 hours 204/1080
400     *         <em>chalakim</em> after sunset on Sunday evening).
401     */
402    public static int getJewishCalendarElapsedDays(int year) {
403        long chalakimSince = getChalakimSinceMoladTohu(year, TISHREI);
404        int moladDay = (int) (chalakimSince / CHALAKIM_PER_DAY);
405        int moladParts = (int) (chalakimSince - moladDay * CHALAKIM_PER_DAY);
406        // delay Rosh Hashana for the 4 dechiyos
407        return addDechiyos(year, moladDay, moladParts);
408    }
409
410    /**
411     * Adds the 4 dechiyos for <em>molad</em> Tishrei. These are:
412     * <ol>
413     * <li><em>Lo ADU Rosh</em> - Rosh Hashana can't fall on a Sunday, Wednesday or Friday. If the <em>molad</em> fell on one
414     * of these days, Rosh Hashana is delayed to the following day.</li>
415     * <li><em>Molad Zaken</em> - If the <em>molad</em> of Tishrei falls after 12 noon, Rosh Hashana is delayed to the following
416     * day. If the following day is <em>ADU</em>, it will be delayed an additional day.</li>
417     * <li><em>GaTRaD</em> - If on a non leap year the <em>molad</em> of Tishrei falls on a Tuesday (Ga) on or after 9 hours
418     * (<em>T</em>) and (<em>RaD</em> 204 <em>chalakim</em> it is delayed till Thursday (one day delay, plus one day for
419     * <em>Lo ADU Rosh</em>)</li>
420     * <li><em>BeTuTaKPaT</em> - if the year following a leap year falls on a Monday (<em>Be</em>) on or after 15 hours
421     * (<em>Tu</em>) and 589 <em>chalakim</em> (<em>TaKPaT</em>) it is delayed till Tuesday</li>
422     * </ol>
423     *
424     * @param year the year
425     * @param moladDay the <em>molad</em> day
426     * @param moladParts the <em>molad</em> parts
427     * @return the number of elapsed days in the JewishCalendar adjusted for the 4 dechiyos.
428     */
429    private static int addDechiyos(int year, int moladDay, int moladParts) {
430        int roshHashanaDay = moladDay; // if no dechiyos
431        // delay Rosh Hashana for the dechiyos of the Molad - new moon 1 - Molad Zaken, 2- GaTRaD 3- BeTuTaKPaT
432        if ((moladParts >= 19440) // Dechiya of Molad Zaken - molad is >= midday (18 hours * 1080 chalakim)
433                || (((moladDay % 7) == 2) // start Dechiya of GaTRaD - Ga = is a Tuesday
434                && (moladParts >= 9924) // TRaD = 9 hours, 204 parts or later (9 * 1080 + 204)
435                && !isJewishLeapYear(year)) // of a non-leap year - end Dechiya of GaTRaD
436                || (((moladDay % 7) == 1) // start Dechiya of BeTuTaKPaT - Be = is on a Monday
437                && (moladParts >= 16789) // TUTaKPaT part of BeTuTaKPaT = 15 hours, 589 parts or later (15 * 1080 + 589)
438                && (isJewishLeapYear(year - 1)))) { // in a year following a leap year - end Dechiya of BeTuTaKPaT
439            roshHashanaDay += 1; // Then postpone Rosh HaShanah one day
440        }
441        // start 4th Dechiya - Lo ADU Rosh - Rosh Hashana can't occur on A- sunday, D- Wednesday, U - Friday
442        if (((roshHashanaDay % 7) == 0)// If Rosh HaShanah would occur on Sunday,
443                || ((roshHashanaDay % 7) == 3) // or Wednesday,
444                || ((roshHashanaDay % 7) == 5)) { // or Friday - end 4th Dechiya - Lo ADU Rosh
445            roshHashanaDay = roshHashanaDay + 1; // Then postpone it one (more) day
446        }
447        return roshHashanaDay;
448    }
449
450    /**
451     * Returns the number of <em>chalakim</em> (parts - 1080 to the hour) from the original hypothetical <em>Molad Tohu</em>
452     * to the year and month passed in.
453     *
454     * @param year the Jewish year
455     * @param month the Jewish month the Jewish month, with the month numbers starting from Nissan. Use the JewishDate constants such
456     *         as {@link JewishDate#TISHREI}.
457     * @return the number of <em>chalakim</em> (parts - 1080 to the hour) from the original hypothetical <em>Molad Tohu</em>
458     */
459    private static long getChalakimSinceMoladTohu(int year, int month) {
460         int y = year - 1;
461                // Jewish lunar month = 29 days, 12 hours and 793 chalakim
462                // chalakim since Molad Tohu BeHaRaD - 1 day, 5 hours and 204 chalakim
463                int monthOfYear = getJewishMonthOfYear(year, month);
464                int monthsElapsed = (235 * (y / 19)) // Months in complete 19-year lunar (Metonic) cycles so far
465                 + (12 * (y % 19)) // Regular months in this cycle
466                 + ((7 * (y % 19) + 1) / 19) // Leap months this cycle
467                 + (monthOfYear - 1); // add elapsed months till the start of the molad of the month
468         // return chalakim prior to BeHaRaD + number of chalakim since
469         return CHALAKIM_MOLAD_TOHU + (CHALAKIM_PER_MONTH * monthsElapsed);
470    }
471
472    /**
473     * Returns the number of <em>chalakim</em> (parts - 1080 to the hour) from the original hypothetical <em>Molad Tohu</em>
474     * to the Jewish year and month that this Object is set to.
475     *
476     * @return the number of <em>chalakim</em> (parts - 1080 to the hour) from the original hypothetical <em>Molad Tohu</em>
477     */
478    public long getChalakimSinceMoladTohu() {
479        return getChalakimSinceMoladTohu(jewishYear, jewishMonth);
480    }
481
482    /**
483     * Converts the {@link JewishDate#NISSAN} based constants used by this class to numeric month starting from
484     * {@link JewishDate#TISHREI}. This is required for <em>molad</em> calculations.
485     *
486     * @param year The Jewish year
487     * @param month The Jewish Month
488     * @return the Jewish month of the year starting with Tishrei
489     */
490    private static int getJewishMonthOfYear(int year, int month) {
491        boolean isLeapYear = isJewishLeapYear(year);
492        return (month + (isLeapYear ? 6 : 5)) % (isLeapYear ? 13 : 12) + 1;
493    }
494
495    /**
496     * Validates the components of a Jewish date for validity. It will throw an {@link IllegalArgumentException} if the Jewish
497     * date is earlier than 18 Teves, 3761 (1/1/1 Gregorian), a month &lt; 1 or &gt; 12 (or 13 on a {@link #isJewishLeapYear(int)
498     * leap year}), the day of month is &lt; 1 or &gt; 30, an hour &lt; 0 or &gt; 23, a minute &lt; 0 or &gt; 59 or
499     * <em>chalakim</em> &lt; 0 or &gt; 17. For larger a larger number of <em>chalakim</em> such as 793 (TaShTzaG) break the
500     * <em>chalakim</em> into minutes (18 <em>chalakim</em> per minutes, so it would be 44 minutes and 1 <em>chelek</em> in the
501     * case of 793 / <em>TaShTzaG</em>).
502     *
503     * @param year the Jewish year to validate. It will reject any year &lt;= 3761 (lower than the year 1 Gregorian).
504     * @param month the Jewish month to validate. It will reject a month &lt; 1 or &gt; 12 (or 13 on a leap year) .
505     * @param dayOfMonth the day of the Jewish month to validate. It will reject any value &lt; 1 or &gt; 30 TODO: check calling
506     *         methods to see if there is any reason that the class can validate that 30 is invalid for some months.
507     * @param hours the hours (for <em>molad</em> calculations). It will reject an hour &lt; 0 or &gt; 23
508     * @param minutes the minutes (for <em>molad</em> calculations). It will reject a minute &lt; 0 or &gt; 59
509     * @param chalakim the <em>chalakim</em> / parts (for <em>molad</em> calculations). It will reject a <em>chalakim</em> &lt; 0 or
510     *         &gt; 17. For larger numbers such as 793 (<em>TaShTzaG</em>) break the <em>chalakim</em> into minutes (18
511     *         <em>chalakim</em> per minutes, so it would be 44  minutes and 1 <em>chelek</em> in the case of 793 / <em>TaShTzaG</em>)
512     *
513     * @throws IllegalArgumentException if a Jewish date earlier than 18 Teves, 3761 (1/1/1 Gregorian), a month &lt; 1 or &gt; 12 (or
514     *         13 on a leap year), the day of month is &lt; 1 or &gt; 30, an hour &lt; 0 or &gt; 23, a minute &lt; 0 or &gt; 59 or
515     *         <em>chalakim</em> &lt; 0 or &gt; 17. For larger a larger number of <em>chalakim</em> such as 793 (<em>TaShTzaG</em>)
516     *         break the <em>chalakim</em> into minutes (18 <em>chalakim</em> per minutes, so it would be 44 minutes and 1
517     *         <em>chelek</em> in the case of 793 (<em>TaShTzaG</em>).
518     */
519    private static void validateJewishDate(int year, int month, int dayOfMonth, int hours, int minutes, int chalakim) {
520        if (month < NISSAN || month > getLastMonthOfJewishYear(year)) {
521            throw new IllegalArgumentException("The Jewish month has to be between 1 and 12 (or 13 on a leap year). "
522                    + month + " is invalid for the year " + year + ".");
523        }
524        int monthLength = getDaysInJewishMonth(year, month);
525        if (dayOfMonth < 1 || dayOfMonth > monthLength) {
526                HebrewDateFormatter hdf = new HebrewDateFormatter();
527                String monthName = hdf.getTransliteratedMonthList()[month];
528            throw new IllegalArgumentException(
529                    "The Jewish day of month can't be < 1 or > " + monthLength +
530                            " for the month index " + monthName + ", day  " + dayOfMonth + " is invalid.");
531        }
532        // reject dates prior to 18 Teves, 3761 (1/1/1 AD). This restriction can be relaxed if the date coding is
533        // changed/corrected
534        if ((year < 3761) || (year == 3761 && (month >= TISHREI && month < TEVES))
535                || (year == 3761 && month == TEVES && dayOfMonth < 18)) {
536            throw new IllegalArgumentException(
537                    "A Jewish date earlier than 18 Teves, 3761 (1/1/1 Gregorian) can't be set. " + year + ", " + month
538                            + ", " + dayOfMonth + " is invalid.");
539        }
540        if (hours < 0 || hours > 23) {
541            throw new IllegalArgumentException("Hours < 0 or > 23 can't be set. " + hours + " is invalid.");
542        }
543
544        if (minutes < 0 || minutes > 59) {
545            throw new IllegalArgumentException("Minutes < 0 or > 59 can't be set. " + minutes + " is invalid.");
546        }
547
548        if (chalakim < 0 || chalakim > 17) {
549            throw new IllegalArgumentException(
550                    "Chalakim/parts < 0 or > 17 can't be set. "
551                            + chalakim
552                            + " is invalid. For larger numbers such as 793 (TaShTzaG) break the <em>chalakim</em> into minutes (18 chalakim per minutes, so it would be 44 minutes and 1 chelek in the case of 793 (TaShTzaG)");
553        }
554    }
555
556    /**
557     * Returns the number of days for a given Jewish year. ND+ER
558     *
559     * @param year the Jewish year
560     * @return the number of days for a given Jewish year.
561     * @see #isCheshvanLong()
562     * @see #isKislevShort()
563     */
564    public static int getDaysInJewishYear(int year) {
565        return getJewishCalendarElapsedDays(year + 1) - getJewishCalendarElapsedDays(year);
566    }
567
568    /**
569     * Returns the number of days for the current year that the calendar is set to.
570     *
571     * @return the number of days for the Object's current Jewish year.
572     * @see #isCheshvanLong()
573     * @see #isKislevShort()
574     * @see #isJewishLeapYear()
575     */
576    public int getDaysInJewishYear() {
577        return getDaysInJewishYear(getJewishYear());
578    }
579
580    /**
581     * Returns if Cheshvan is long in a given Jewish year. The method name isLong is done since in a Kesidran (ordered)
582     * year Cheshvan is short. ND+ER
583     *
584     * @param year the year
585     * @return true if Cheshvan is long in Jewish year.
586     * @see #isCheshvanLong()
587     * @see #getCheshvanKislevKviah()
588     */
589    private static boolean isCheshvanLong(int year) {
590        return getDaysInJewishYear(year) % 10 == 5;
591    }
592
593    /**
594     * Returns if Cheshvan is long (30 days VS 29 days) for the current year that the calendar is set to. The method
595     * name isLong is done since in a Kesidran (ordered) year Cheshvan is short.
596     *
597     * @return true if Cheshvan is long for the current year that the calendar is set to
598     * @see #isCheshvanLong()
599     */
600    public boolean isCheshvanLong() {
601        return isCheshvanLong(getJewishYear());
602    }
603
604    /**
605     * Returns if Kislev is short (29 days VS 30 days) in a given Jewish year. The method name isShort is done since in
606     * a Kesidran (ordered) year Kislev is long. ND+ER
607     *
608     * @param year the Jewish year
609     * @return true if Kislev is short for the given Jewish year.
610     * @see #isKislevShort()
611     * @see #getCheshvanKislevKviah()
612     */
613    private static boolean isKislevShort(int year) {
614        return getDaysInJewishYear(year) % 10 == 3;
615    }
616
617    /**
618     * Returns if the Kislev is short for the year that this class is set to. The method name isShort is done since in a
619     * Kesidran (ordered) year Kislev is long.
620     *
621     * @return true if Kislev is short for the year that this class is set to
622     */
623    public boolean isKislevShort() {
624        return isKislevShort(getJewishYear());
625    }
626
627    /**
628     * Returns the Cheshvan and Kislev kviah (whether a Jewish year is short, regular or long). It will return
629     * {@link #SHELAIMIM} if both cheshvan and kislev are 30 days, {@link #KESIDRAN} if Cheshvan is 29 days and Kislev
630     * is 30 days and {@link #CHASERIM} if both are 29 days.
631     *
632     * @return {@link #SHELAIMIM} if both cheshvan and kislev are 30 days, {@link #KESIDRAN} if Cheshvan is 29 days and
633     *        Kislev is 30 days and {@link #CHASERIM} if both are 29 days.
634     * @see #isCheshvanLong()
635     * @see #isKislevShort()
636     */
637    public int getCheshvanKislevKviah() {
638        if (isCheshvanLong() && !isKislevShort()) {
639            return SHELAIMIM;
640        } else if (!isCheshvanLong() && isKislevShort()) {
641            return CHASERIM;
642        } else {
643            return KESIDRAN;
644        }
645    }
646
647    /**
648     * Returns the number of days of a Jewish month for a given month and year.
649     *
650     * @param year the Jewish Year
651     * @param month the Jewish month
652     * @return the number of days for a given Jewish month
653     */
654    private static int getDaysInJewishMonth(int year, int month) {
655        if ((month == IYAR) || (month == TAMMUZ) || (month == ELUL) || ((month == CHESHVAN) && !(isCheshvanLong(year)))
656                || ((month == KISLEV) && isKislevShort(year)) || (month == TEVES)
657                || ((month == ADAR) && !(isJewishLeapYear(year))) || (month == ADAR_II)) {
658            return 29;
659        } else {
660            return 30;
661        }
662    }
663
664    /**
665     * Returns the number of days of the Jewish month that the calendar is currently set to.
666     *
667     * @return the number of days for the Jewish month that the calendar is currently set to.
668     */
669    public int getDaysInJewishMonth() {
670        return getDaysInJewishMonth(getJewishYear(), getJewishMonth());
671    }
672
673    /**
674     * Computes and sets the Jewish date fields based on the provided absolute (Gregorian) date. The date may be before
675     * January 1, 0001, as the <em>molad</em> of Teves 3761 is, on December 12, 0000.
676     * @param gregorianAbsDate the Gregorian absolute date.
677     */
678    private synchronized void setAbsDate(int gregorianAbsDate) {
679        this.gregorianAbsDate = gregorianAbsDate;
680        // Approximation from below
681        jewishYear = (gregorianAbsDate - JEWISH_EPOCH) / 366;
682        // Search forward for year from the approximation
683        while (gregorianAbsDate >= jewishDateToAbsDate(jewishYear + 1, TISHREI, 1)) {
684            jewishYear++;
685        }
686        // Search forward for month from either Tishri or Nissan.
687        if (gregorianAbsDate < jewishDateToAbsDate(jewishYear, NISSAN, 1)) {
688            jewishMonth = TISHREI;// Start at Tishri
689        } else {
690            jewishMonth = NISSAN;// Start at Nissan
691        }
692        while (gregorianAbsDate > jewishDateToAbsDate(jewishYear, jewishMonth, getDaysInJewishMonth())) {
693            jewishMonth++;
694        }
695        // Calculate the day by subtraction
696        jewishDay = gregorianAbsDate - jewishDateToAbsDate(jewishYear, jewishMonth, 1) + 1;
697
698        // day of week, with floorMod so that a date before January 1, 0001 gets the right day
699        dayOfWeek = Math.floorMod(gregorianAbsDate, 7) + 1;
700    }
701
702    /**
703     * Returns the absolute date of Jewish date. ND+ER
704     *
705     * @param year the Jewish year. The year can't be negative
706     * @param month the Jewish month starting with Nissan. Nissan expects a value of 1 etc. until Adar with a value of 12. For a
707     *         leap year, 13 will be the expected value for Adar II. Use the constants {@link JewishDate#NISSAN} etc.
708     * @param dayOfMonth the Jewish day of month. valid values are 1-30. If the day of month is set to 30 for a month that only
709     *         has 29 days, the day will be set as 29.
710     * @return the absolute date of the Jewish date.
711     */
712    private static int jewishDateToAbsDate(int year, int month, int dayOfMonth) {
713        int elapsed = getDaysSinceStartOfJewishYear(year, month, dayOfMonth);
714        // add elapsed days this year + Days in prior years + Days elapsed before absolute year 1
715        return elapsed + getJewishCalendarElapsedDays(year) + JEWISH_EPOCH;
716    }
717
718    /**
719     * Returns the <em>molad</em> for a given year and month. Returns a JewishDate {@link Object} set to the date of the <em>molad</em>
720     * with the {@link #getMoladHours() hours}, {@link #getMoladMinutes() minutes} and {@link #getMoladChalakim()
721     * chalakim} set. In the current implementation, it sets the <em>molad</em> time based on a midnight date rollover. This
722     * means that Rosh Chodesh Adar II, 5771 with a <em>molad</em> of 7 <em>chalakim</em> past midnight on Shabbos 29 Adar I / March 5,
723     * 2011 12:00 AM and 7 chalakim, will have the following values: hours: 0, minutes: 0, Chalakim: 7.
724     *
725     * @return a JewishDate {@link Object} set to the date of the <em>molad</em> with the {@link #getMoladHours() hours},
726     *         {@link #getMoladMinutes() minutes} and {@link #getMoladChalakim() <em>chalakim</em>} set.
727     */
728    public JewishDate getMolad() {
729        JewishDate moladDate = new JewishDate(getChalakimSinceMoladTohu());
730        if (moladDate.getMoladHours() >= 6) {
731            moladDate.plusDays(1);
732        }
733        moladDate.setMoladHours((moladDate.getMoladHours() + 18) % 24);
734        return moladDate;
735    }
736
737    /**
738     * Returns the number of days from the Jewish epoch from the number of <em>chalakim</em> from the epoch passed in.
739     *
740     * @param chalakim the number of <em>chalakim</em> since the beginning of Sunday prior to BaHaRaD
741     * @return the number of days from the Jewish epoch
742     */
743    private static int moladToAbsDate(long chalakim) {
744        return (int) (chalakim / CHALAKIM_PER_DAY) + JEWISH_EPOCH;
745    }
746
747    /**
748     * Constructor that creates a JewishDate based on a <em>molad</em> passed in. The <em>molad</em> would be the number of
749     * <em>chalakim</em> / parts starting at the beginning of Sunday prior to the <em>Molad Tohu BeHaRaD</em> (<em>Be</em> =
750     * Monday, <em>Ha</em> = 5 hours and <em>RaD</em> = 204 <em>chalakim</em> / parts) - prior to the start of the Jewish
751     * calendar. <em>BeHaRaD</em> is 23:11:20 on Sunday night(5 hours 204/1080 <em>chalakim</em> after sunset on Sunday evening).
752     *
753     * @param molad the number of <em>chalakim</em> since the beginning of Sunday prior to BaHaRaD
754     */
755    public JewishDate(long molad) {
756        setAbsDate(moladToAbsDate(molad));
757        int conjunctionDay = (int) (molad / CHALAKIM_PER_DAY);
758        int chalakim = (int) (molad - conjunctionDay * CHALAKIM_PER_DAY);
759        setMoladHours(chalakim / CHALAKIM_PER_HOUR);
760        chalakim = chalakim - (getMoladHours() * CHALAKIM_PER_HOUR);
761        setMoladMinutes(chalakim / CHALAKIM_PER_MINUTE);
762        setMoladChalakim(chalakim - moladMinutes * CHALAKIM_PER_MINUTE);
763    }
764
765    /**
766     * returns the number of days from Rosh Hashana of the date passed in, to the full date passed in.
767     *
768     * @param year the Jewish year
769     * @param month the Jewish month
770     * @param dayOfMonth the day in the Jewish month
771     * @return the number of days
772     */
773    private static int getDaysSinceStartOfJewishYear(int year, int month, int dayOfMonth) {
774        int elapsedDays = dayOfMonth;
775        // Before Tishrei (from Nissan to Tishrei), add days in prior months
776        if (month < TISHREI) {
777            // this year before and after Nissan.
778            for (int m = TISHREI; m <= getLastMonthOfJewishYear(year); m++) {
779                elapsedDays += getDaysInJewishMonth(year, m);
780            }
781            for (int m = NISSAN; m < month; m++) {
782                elapsedDays += getDaysInJewishMonth(year, m);
783            }
784        } else { // Add days in prior months this year
785            for (int m = TISHREI; m < month; m++) {
786                elapsedDays += getDaysInJewishMonth(year, m);
787            }
788        }
789        return elapsedDays;
790    }
791
792    /**
793     * returns the number of days from Rosh Hashana of the date passed in, to the full date passed in.
794     *
795     * @return the number of days
796     */
797    public int getDaysSinceStartOfJewishYear() {
798        return getDaysSinceStartOfJewishYear(getJewishYear(), getJewishMonth(), getJewishDayOfMonth());
799    }
800
801    /**
802     * Creates a Jewish date based on a Jewish year, month and day of month.
803     *
804     * @param jewishYear the Jewish year
805     * @param jewishMonth the Jewish month. The method expects a 1 for Nissan ... 12 for Adar and 13 for Adar II. Use the constants
806     *         {@link #NISSAN} ... {@link #ADAR} (or {@link #ADAR_II} for a leap year Adar II) to avoid any confusion.
807     * @param jewishDayOfMonth the Jewish day of month. If 30 is passed in for a month with only 29 days (for example {@link #IYAR},
808     *         or {@link #KISLEV} in a year that {@link #isKislevShort()}), the 29th (last valid date of the month) will be set.
809     * @throws IllegalArgumentException if the day of month is &lt; 1 or &gt; 30, or a year of &lt; 0 is passed in.
810     */
811    public JewishDate(int jewishYear, int jewishMonth, int jewishDayOfMonth) {
812        setJewishDate(jewishYear, jewishMonth, jewishDayOfMonth);
813    }
814
815    /**
816     * Default constructor will set a default date to the current system date.
817     */
818    public JewishDate() {
819        resetDate();
820    }
821
822    /**
823     * A constructor that initializes the date to the {@link ZonedDateTime} parameter.
824     *
825     * @param zonedDateTime the <code>ZonedDateTime</code> to set the calendar to
826     */
827    public JewishDate(ZonedDateTime zonedDateTime) {
828        setGregorianDate(zonedDateTime);
829    }
830
831    /**
832     * A constructor that initializes the date to the {@link LocalDate} parameter.
833     *
834     * @param localDate the <code>LocalDate</code> to set the calendar to
835     */
836    public JewishDate(LocalDate localDate) {
837        setGregorianDate(localDate);
838    }
839
840    /**
841     * Sets the date based on a {@link ZonedDateTime} object. Modifies the Jewish date as well.
842     *
843     * @param zonedDateTime the {@link ZonedDateTime} to set the calendar to
844     */
845    public void setGregorianDate(ZonedDateTime zonedDateTime) {
846        setGregorianDate(zonedDateTime.toLocalDate());
847    }
848
849    /**
850     * Sets the date based on a {@link LocalDate} object. Modifies the Jewish date as well.
851     *
852     * @param localDate the <code>LocalDate</code> to set the calendar to
853     * @throws IllegalArgumentException if the date would fall prior to the year 1 AD
854     */
855    public void setGregorianDate(LocalDate localDate) {
856        int absDate = gregorianDateToAbsDate(localDate.getYear(),  localDate.getMonth().getValue(), localDate.getDayOfMonth());
857        if (absDate <= 0) {
858            throw new IllegalArgumentException("Dates in the BC era are not supported");
859        }
860        setAbsDate(absDate); // convert to Jewish date
861    }
862
863    /**
864     * Sets the Jewish Date and updates the Gregorian date accordingly.
865     *
866     * @param year the Jewish year. The year can't be negative
867     * @param month the Jewish month starting with Nissan. A value of 1 is expected for Nissan ... 12 for Adar and 13 for Adar II.
868     *         Use the constants {@link #NISSAN} ... {@link #ADAR} (or {@link #ADAR_II} for a leap year Adar II) to avoid any
869     *         confusion.
870     * @param dayOfMonth the Jewish day of month. valid values are 1-30. If the day of month is set to 30 for a month that only
871     *         has 29 days, the day will be set as 29.
872     * @throws IllegalArgumentException if a Jewish date earlier than 18 Teves, 3761 (1/1/1 Gregorian), a month &lt; 1 or &gt; 12
873     *         (or 13 on a leap year) or the day of month is &lt; 1 or &gt; 30 is passed in
874     */
875    public void setJewishDate(int year, int month, int dayOfMonth) {
876        setJewishDate(year, month, dayOfMonth, getMoladHours(), getMoladMinutes(), getMoladChalakim());
877    }
878
879    /**
880     * Sets the Jewish Date and updates the Gregorian date accordingly.
881     *
882     * @param year the Jewish year. The year can't be negative
883     * @param month the Jewish month starting with Nissan. A value of 1 is expected for Nissan ... 12 for Adar and 13 for Adar II.
884     *         Use the constants {@link #NISSAN} ... {@link #ADAR} (or {@link #ADAR_II} for a leap year Adar II) to avoid any
885     *         confusion.
886     * @param dayOfMonth the Jewish day of month. valid values are 1-30. If the day of month is set to 30 for a month that only
887     *         has 29 days, the day will be set as 29.
888     * @param hours the hour of the day. Used for <em>molad</em> calculations
889     * @param minutes the minutes. Used for <em>molad</em> calculations
890     * @param chalakim the <em>chalakim</em> / parts. Used for <em>molad</em> calculations. The <em>chalakim</em> should not exceed
891     *         17. Minutes should be used for larger numbers.
892     *
893     * @throws IllegalArgumentException if a Jewish date earlier than 18 Teves, 3761 (1/1/1 Gregorian), a month &lt; 1 or &gt; 12 (or
894     *         13 on a leap year), the day of month is &lt; 1 or &gt; 30, an hour &lt; 0 or &gt; 23, a minute &lt; 0 &gt; 59 or
895     *         <em>chalakim</em> &lt; 0 &gt; 17. For larger a larger number of <em>chalakim</em> such as 793 (<em>TaShTzaG</em>)
896     *         break the <em>chalakim</em> into minutes (18 <em>chalakim</em> per minutes, so it would be 44 minutes and 1
897     *         <em>chelek</em> in the case of 793 (<em>TaShTzaG</em>).
898     */
899    public synchronized void setJewishDate(int year, int month, int dayOfMonth, int hours, int minutes, int chalakim) {
900
901        validateJewishDate(year, month, dayOfMonth, hours, minutes, chalakim);
902
903        jewishYear = year;
904        jewishMonth = month;
905        jewishDay = dayOfMonth;
906        moladHours = hours;
907        moladMinutes = minutes;
908        moladChalakim = chalakim;
909
910        gregorianAbsDate = jewishDateToAbsDate(jewishYear, jewishMonth, jewishDay); // reset Gregorian date
911
912        dayOfWeek = Math.abs(gregorianAbsDate % 7) + 1; // reset day of week
913    }
914
915    /**
916     * Setter for the Jewish day of the month that will be <a href="https://en.wikipedia.org/wiki/Clamp_(function)"
917     * >clamped</a> to the lesser of the number passed in or the max number of days in the month.
918     * @param dayOfMonth the day of the month to set the date to.
919     */
920    public void setJewishDayOfMonth(int dayOfMonth){
921        setJewishDate(getJewishYear(), getJewishMonth(), dayOfMonth);
922    }
923
924    /**
925     * Setter for the Jewish month that is passed in. If the day of month is currently the 30th and the month is being set to
926     * a month that only has 29 days, the day of month will be <a href="https://en.wikipedia.org/wiki/Clamp_(function)"
927     * >clamped</a> to the 29th of the month.
928     * @param month the month to be set
929     */
930    public void setJewishMonth(int month){
931        int year = getJewishYear();
932        int day = Math.min(getDaysInJewishMonth(year, month), getJewishDayOfMonth());
933        setJewishDate(year, month, day);
934    }
935
936    /**
937     * Setter for the Jewish year of the passed in that will <a href="https://en.wikipedia.org/wiki/Clamp_(function)"
938     * >clamp</a> the day to the month to the lesser of the current day and the max number of days in the month (if set
939     * to the 30th).
940     *
941     * Note that if you are using this for a yahrzeit (or any other reason)on the 30th of the month that will not always have
942     * 30 days, such as {@link #CHESHVAN} or {@link #KISLEV} or {@link #ADAR ADAR I} on a leap year and the next year is a
943     * non-leap year, you must clone your date or once it is set to the 29th, the next time you forward it to a year that has
944     * 30 days, the calendar will incorrectly be forwarded a year from the 29th to the 29th and not the 30th that you may expect.
945     * @param year the year to set.
946     */
947    public void setJewishYear(int year){
948        int month = Math.min(getJewishMonth(), getLastMonthOfJewishYear(year));
949        int day = Math.min(getJewishDayOfMonth(), getDaysInJewishMonth(year, month));
950        setJewishDate(year, month, day);
951    }
952
953
954    /**
955     * Returns this object's date as a {@link LocalDate} object.
956     *
957     * @return The {@link LocalDate}
958     */
959    public LocalDate getLocalDate() {
960        return absDateToDate(getAbsDate());
961    }
962
963    /**
964     * Resets this date to the current system date.
965     */
966    public void resetDate() {
967        LocalDate localDate = LocalDate.now();
968        setGregorianDate(localDate);
969    }
970
971    /**
972     * Subtracts the number of days passed in from the currently set date.
973     * @param days the number of days to subtract.
974     * @see plusDays(int)
975     */
976    public void minusDays(int days){
977        if (days < 1) {
978            throw new IllegalArgumentException("The number of days to subtract must be greater than zero.");
979        }
980        int absDate = getAbsDate() - days;
981        if (absDate <= 0) {
982            throw new IllegalArgumentException("Dates in the BC era are not supported");
983        }
984        setAbsDate(absDate);
985
986    }
987
988    /**
989     * Add the number of days passed in to the currently set date.
990     * @param days the number of days to add.
991     * @see minusDays(int)
992     */
993    public void plusDays(int days){
994        if (days < 1) {
995            throw new IllegalArgumentException("The number of days to add must be greater than zero. Use minusDays(int) to subtract days.");
996        }
997        setAbsDate(getAbsDate() + days);
998    }
999
1000    /**
1001     * Add the number of months passed in to the currently set date. If the day of the month prior to addition is the 30th, and
1002     * the target month only has 29 days, the date will be clamped to the 29th.
1003     * @param months the number of months to add.
1004     * @see minusMonths(int)
1005     */
1006    public void plusMonths(int months){
1007        if (months < 1) {
1008            throw new IllegalArgumentException("The number of months to add must be greater than zero. Use minusMonths(int) to subtract months.");
1009        }
1010        int year = getJewishYear();
1011        int month = getJewishMonth();
1012        for (int i = 0; i < months; i++) {
1013            if (month == ELUL) {
1014                month = TISHREI;
1015                year++;
1016            } else if ((! isJewishLeapYear(year) && month == ADAR)
1017                    || (isJewishLeapYear(year) && month == ADAR_II)){
1018                month = NISSAN;
1019            } else {
1020                month++;
1021            }
1022        }
1023        int day = Math.min(getJewishDayOfMonth(), getDaysInJewishMonth(year, month));
1024        setJewishDate(year, month, day);
1025    }
1026
1027    /**
1028     * Subtracts the number of months passed in to the currently set date. If the day of the month prior to subtraction
1029     * is the 30th, and the target month only has 29 days, the date will be clamped to the 29th.
1030     * @param months the number of months to subtract.
1031     * @see plusMonths(int)
1032     */
1033        public void minusMonths(int months){
1034        if (months < 1) {
1035                throw new IllegalArgumentException("The number of months to subtract must be greater than zero.");
1036        }
1037        int year = getJewishYear();
1038        int month = getJewishMonth();
1039        for (int i = 0; i < months; i++) {
1040                if (month == TISHREI) {
1041                        month = ELUL;
1042                        year--;
1043                } else if (month == NISSAN) {
1044                        month = getLastMonthOfJewishYear(year);
1045                } else if (!isJewishLeapYear(year) && month == ADAR){
1046                        month = SHEVAT;
1047                } else {
1048                        month--;
1049                }
1050        }
1051        int day = Math.min(getJewishDayOfMonth(), getDaysInJewishMonth(year, month));
1052        setJewishDate(year, month, day);
1053    }
1054
1055    /**
1056     * Add the number of years passed in to the currently set date. If the current month is Adar on a non-leap year,
1057     * and the year after the addition will be a leap year, passing <code>true</code> to the useAdarAlephForLeapYear
1058     * parameter will set the month to Adar I, and passing <code>false</code> will forward it to Adar II. The
1059     * useAdarAlephForLeapYear will be ignored if the month is not Adar. If the current year is a leap year and it is
1060     * currently Adar I or Adar II and the year it is being increased to is also a leap year, the same Adar will be used.
1061     * If it is being increased to a non-leap year, the month will be set to Adar. It is important to keep in mind when
1062     * calculating <em>yahrzits</em> that are on the 30th and the target year only has 29 days, that the date will be set
1063     * to the 29th, something that may nt be desirable.
1064     * @param years the number of years to add
1065     * @param useAdarAlephForLeapYear if set to true and the current month is Adar on a non-leap year and it is being moved
1066     *         forward to a leap year, it will be set to Adar I, and if set to false it will set to Adar II. This will be ignored if
1067     *         the month is not set to Adar.
1068     * @see minusYears(int, boolean)
1069     */
1070    public void plusYears(int years, boolean useAdarAlephForLeapYear){
1071        if (years < 1) {
1072            throw new IllegalArgumentException("The number of years to add has to be greater than zero. Use minusYears(int, boolean) to subtract years.");
1073        }
1074        int targetYear = getJewishYear() + years;
1075        // If we are in the month of Adar in a non-leap year and we are skipping
1076        // to a year that is a leap year, we will use useAdarAlephInYear do
1077        // decide which month to skip to.
1078        int month;
1079        if (getJewishMonth() == JewishDate.ADAR && !isJewishLeapYear(getJewishYear()) && isJewishLeapYear(targetYear)){
1080            if (useAdarAlephForLeapYear){
1081                month = JewishDate.ADAR;
1082            }else{
1083                month = JewishDate.ADAR_II;
1084            }
1085        } else{
1086            // If we are in JewishDate.ADAR_II, this will clamp the month to 12 (JewishDate.ADAR)
1087            month = Math.min(getJewishMonth(), getLastMonthOfJewishYear(targetYear));
1088        }
1089        // Clamp to final day of the month
1090        int day = Math.min(getJewishDayOfMonth(), getDaysInJewishMonth(targetYear, month));
1091        setJewishDate(targetYear, month, day);
1092    }
1093
1094    /**
1095     * Subtract the number of years passed in to the currently set date. If the current month is Adar on a non-leap year,
1096     * and the year after the subtraction will be a leap year, passing <code>true</code> to the useAdarAlephForLeapYear
1097     * parameter will set the month to Adar I, and passing <code>false</code> will set it to Adar II. The
1098     * useAdarAlephForLeapYear will be ignored if the current month is not Adar on a non-leap year. If the current year
1099     * is a leap year and it is currently Adar I or Adar II and the year it is being decreased to is also a leap year,
1100     * the same Adar will be used. If it is being decreased to a non-leap year, the month will be set to Adar.
1101     * @param years the number of years to subtract
1102     * @param useAdarAlephForLeapYear if set to true and the current month is Adar on a non-leap year and it is being
1103     *         subtracted to a leap year, it will be set to Adar I, and if set to false it will set to Adar II. This will
1104     *         be ignored if the month is not set to Adar.
1105     * @see plusYears(int, boolean)
1106     */
1107    public void minusYears(int years, boolean useAdarAlephForLeapYear){
1108        if (years < 1) {
1109            throw new IllegalArgumentException("The number of years to subtract has to be greater than zero.");
1110        }
1111        int targetYear = getJewishYear() - years;
1112        // If we are in the month of Adar in a non-leap year and we are skipping
1113        // to a year that is a leap year, we will use useAdarAlephInYear do
1114        // decide which month to skip to.
1115        int month;
1116        if (getJewishMonth() == JewishDate.ADAR && !isJewishLeapYear(getJewishYear()) && isJewishLeapYear(targetYear)){
1117            if (useAdarAlephForLeapYear){
1118                month = JewishDate.ADAR;
1119            }else{
1120                month = JewishDate.ADAR_II;
1121            }
1122        } else{
1123            // If we are in JewishDate.ADAR_II, this will clamp the month to 12 (JewishDate.ADAR)
1124            month = Math.min(getJewishMonth(), getLastMonthOfJewishYear(targetYear));
1125        }
1126        // Clamp to final day of the month
1127        int day = Math.min(getJewishDayOfMonth(), getDaysInJewishMonth(targetYear, month));
1128        setJewishDate(targetYear, month, day);
1129    }
1130
1131    /**
1132     * Returns a string containing the Jewish date in the form, "day Month, year" e.g. "21 Shevat, 5729". For more
1133     * complex formatting, use the formatter classes.
1134     *
1135     * @return the Jewish date in the form "day Month, year" e.g. "21 Shevat, 5729"
1136     * @see HebrewDateFormatter#format(JewishDate)
1137     */
1138    @Override
1139    public String toString() {
1140        return new HebrewDateFormatter().format(this);
1141    }
1142
1143    /**
1144     * Indicates whether some other object is "equal to" this one.
1145     * @see Object#equals(Object)
1146     */
1147    public boolean equals(Object object) {
1148        if (this == object) {
1149            return true;
1150        }
1151        if (object == null || getClass() != object.getClass()) {
1152            return false;
1153        }
1154        JewishDate jewishDate = (JewishDate) object;
1155        return gregorianAbsDate == jewishDate.getAbsDate();
1156    }
1157
1158    /**
1159     * Compares two dates as per the compareTo() method in the Comparable interface. Returns a value less than 0 if this
1160     * date is "less than" (before) the date, greater than 0 if this date is "greater than" (after) the date, or 0 if
1161     * they are equal.
1162     */
1163    public int compareTo(JewishDate jewishDate) {
1164        return Integer.compare(gregorianAbsDate, jewishDate.getAbsDate());
1165    }
1166
1167    /**
1168     * Returns the Jewish month 1-12 (or 13 years in a leap year). The month count starts with 1 for Nissan and goes to
1169     * 13 for Adar II
1170     *
1171     * @return the Jewish month from 1 to 12 (or 13 years in a leap year). The month count starts with 1 for Nissan and
1172     *         goes to 13 for Adar II
1173     */
1174    public int getJewishMonth() {
1175        return jewishMonth;
1176    }
1177
1178    /**
1179     * Returns the Jewish day of month.
1180     *
1181     * @return the Jewish day of the month
1182     */
1183    public int getJewishDayOfMonth() {
1184        return jewishDay;
1185    }
1186
1187    /**
1188     * Returns the Jewish year.
1189     *
1190     * @return the Jewish year
1191     */
1192    public int getJewishYear() {
1193        return jewishYear;
1194    }
1195
1196    /**
1197     * Returns the day of the week as a number between 1-7.
1198     *
1199     * @return the day of the week as a number between 1-7.
1200     */
1201    public int getDayOfWeek() {
1202        return dayOfWeek;
1203    }
1204
1205    /**
1206     * A method that creates a <a href="http://en.wikipedia.org/wiki/Object_copy#Deep_copy">deep copy</a> of the object.
1207     *
1208     * @see Object#clone()
1209     */
1210    @Override
1211    public Object clone() {
1212        JewishDate clone = null;
1213        try {
1214            clone = (JewishDate) super.clone();
1215        } catch (CloneNotSupportedException cnse) {
1216            // Required by the compiler. Should never be reached since we implement clone()
1217        }
1218        if (clone != null) {
1219            clone.setAbsDate(getAbsDate());
1220            clone.setMoladHours(getMoladHours());
1221            clone.setMoladMinutes(getMoladMinutes());
1222            clone.setMoladChalakim(getMoladChalakim());
1223        }
1224        return clone;
1225    }
1226
1227    /**
1228     * Overrides {@link Object#hashCode()}.
1229     * @see Object#hashCode()
1230     */
1231    @Override
1232    public int hashCode() {
1233        return Integer.hashCode(gregorianAbsDate);
1234    }
1235}