]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-52_1/main/classes/core/src/com/ibm/icu/util/IslamicCalendar.java
Added flags.
[Dictionary.git] / jars / icu4j-52_1 / main / classes / core / src / com / ibm / icu / util / IslamicCalendar.java
1 /*
2  *******************************************************************************
3  * Copyright (C) 1996-2013, International Business Machines Corporation and    *
4  * others. All Rights Reserved.                                                *
5  *******************************************************************************
6  */
7 package com.ibm.icu.util;
8 import java.io.IOException;
9 import java.io.ObjectInputStream;
10 import java.util.Date;
11 import java.util.Locale;
12
13 import com.ibm.icu.impl.CalendarAstronomer;
14 import com.ibm.icu.impl.CalendarCache;
15 import com.ibm.icu.impl.CalendarUtil;
16 import com.ibm.icu.util.ULocale.Category;
17
18 /**
19  * <code>IslamicCalendar</code> is a subclass of <code>Calendar</code>
20  * that that implements the Islamic civil and religious calendars.  It
21  * is used as the civil calendar in most of the Arab world and the
22  * liturgical calendar of the Islamic faith worldwide.  This calendar
23  * is also known as the "Hijri" calendar, since it starts at the time
24  * of Mohammed's emigration (or "hijra") to Medinah on Thursday, 
25  * July 15, 622 AD (Julian).
26  * <p>
27  * The Islamic calendar is strictly lunar, and thus an Islamic year of twelve
28  * lunar months does not correspond to the solar year used by most other
29  * calendar systems, including the Gregorian.  An Islamic year is, on average,
30  * about 354 days long, so each successive Islamic year starts about 11 days
31  * earlier in the corresponding Gregorian year.
32  * <p>
33  * Each month of the calendar starts when the new moon's crescent is visible
34  * at sunset.  However, in order to keep the time fields in this class
35  * synchronized with those of the other calendars and with local clock time,
36  * we treat days and months as beginning at midnight,
37  * roughly 6 hours after the corresponding sunset.
38  * <p>
39  * There are three main variants of the Islamic calendar in existence.  The first
40  * is the <em>civil</em> calendar, which uses a fixed cycle of alternating 29-
41  * and 30-day months, with a leap day added to the last month of 11 out of
42  * every 30 years.  This calendar is easily calculated and thus predictable in
43  * advance, so it is used as the civil calendar in a number of Arab countries.
44  * This is the default behavior of a newly-created <code>IslamicCalendar</code>
45  * object.
46  * <p>
47  * The Islamic <em>religious</em> calendar and Saudi Arabia's <em>Umm al-Qura</em> 
48  * calendar, however, are based on the <em>observation</em> of the crescent moon.  
49  * It is thus affected by the position at which the
50  * observations are made, seasonal variations in the time of sunset, the
51  * eccentricities of the moon's orbit, and even the weather at the observation
52  * site.  This makes it impossible to calculate in advance, and it causes the
53  * start of a month in the religious calendar to differ from the civil calendar
54  * by up to three days.
55  * <p>
56  * Using astronomical calculations for the position of the sun and moon, the
57  * moon's illumination, and other factors, it is possible to determine the start
58  * of a lunar month with a fairly high degree of certainty.  However, these
59  * calculations are extremely complicated and thus slow, so most algorithms,
60  * including the one used here, are only approximations of the true astronomical
61  * calculations.  At present, the approximations used in this class are fairly
62  * simplistic; they will be improved in later versions of the code.
63  * <p>
64  * Like the Islamic religious calendar, <em>Umm al-Qura</em> is also based 
65  * on the sighting method of the crescent moon but is standardized by Saudi Arabia.
66  * <p>  
67  * The {@link #setType setType} method determines
68  * which approach is used to determine the start of a month.  By default, the
69  * fixed-cycle <em>civil</em> calendar is used.  However, if <code>setType(ISLAMIC)</code>
70  * is called, an approximation of the true lunar calendar will be used.
71  * Similarly, if <code>setType(ISLAMIC_UMALQURA)</code> is called, an approximation 
72  * of the Umm al-Qura lunar calendar will be used.
73  * <p>
74  * This class should not be subclassed.</p>
75  * <p>
76  * IslamicCalendar usually should be instantiated using 
77  * {@link com.ibm.icu.util.Calendar#getInstance(ULocale)} passing in a <code>ULocale</code>
78  * with the tag <code>"@calendar=islamic"</code> or <code>"@calendar=islamic-civil"</code> 
79  * or <code>"@calendar=islamic-umalqura"</code>.</p>
80  *
81  * @see com.ibm.icu.util.GregorianCalendar
82  * @see com.ibm.icu.util.Calendar
83  *
84  * @author Laura Werner
85  * @author Alan Liu
86  * @stable ICU 2.8
87  */
88 public class IslamicCalendar extends Calendar {
89     // jdk1.4.2 serialver
90     private static final long serialVersionUID = -6253365474073869325L;
91
92     //-------------------------------------------------------------------------
93     // Constants...
94     //-------------------------------------------------------------------------
95     
96     /**
97      * Constant for Muharram, the 1st month of the Islamic year. 
98      * @stable ICU 2.8 
99      */
100     public static final int MUHARRAM = 0;
101
102     /**
103      * Constant for Safar, the 2nd month of the Islamic year. 
104      * @stable ICU 2.8 
105      */
106     public static final int SAFAR = 1;
107
108     /**
109      * Constant for Rabi' al-awwal (or Rabi' I), the 3rd month of the Islamic year. 
110      * @stable ICU 2.8 
111      */
112     public static final int RABI_1 = 2;
113
114     /**
115      * Constant for Rabi' al-thani or (Rabi' II), the 4th month of the Islamic year. 
116      * @stable ICU 2.8 
117      */
118     public static final int RABI_2 = 3;
119
120     /**
121      * Constant for Jumada al-awwal or (Jumada I), the 5th month of the Islamic year. 
122      * @stable ICU 2.8 
123      */
124     public static final int JUMADA_1 = 4;
125
126     /**
127      * Constant for Jumada al-thani or (Jumada II), the 6th month of the Islamic year. 
128      * @stable ICU 2.8 
129      */
130     public static final int JUMADA_2 = 5;
131
132     /**
133      * Constant for Rajab, the 7th month of the Islamic year. 
134      * @stable ICU 2.8 
135      */
136     public static final int RAJAB = 6;
137
138     /**
139      * Constant for Sha'ban, the 8th month of the Islamic year. 
140      * @stable ICU 2.8 
141      */
142     public static final int SHABAN = 7;
143
144     /**
145      * Constant for Ramadan, the 9th month of the Islamic year. 
146      * @stable ICU 2.8 
147      */
148     public static final int RAMADAN = 8;
149
150     /**
151      * Constant for Shawwal, the 10th month of the Islamic year. 
152      * @stable ICU 2.8 
153      */
154     public static final int SHAWWAL = 9;
155
156     /**
157      * Constant for Dhu al-Qi'dah, the 11th month of the Islamic year. 
158      * @stable ICU 2.8 
159      */
160     public static final int DHU_AL_QIDAH = 10;
161
162     /**
163      * Constant for Dhu al-Hijjah, the 12th month of the Islamic year. 
164      * @stable ICU 2.8 
165      */
166     public static final int DHU_AL_HIJJAH = 11;
167
168
169     private static final long HIJRA_MILLIS = -42521587200000L;    // 7/16/622 AD 00:00
170
171     /**
172      * Friday EPOC
173      */
174     private static final long CIVIL_EPOC = 1948440;
175     /**
176      * Thursday EPOC
177      */
178     private static final long ASTRONOMICAL_EPOC = 1948439;
179
180     //-------------------------------------------------------------------------
181     // Constructors...
182     //-------------------------------------------------------------------------
183
184     /**
185      * Constructs a default <code>IslamicCalendar</code> using the current time
186      * in the default time zone with the default <code>FORMAT</code> locale.
187      * @see Category#FORMAT
188      * @stable ICU 2.8
189      */
190     public IslamicCalendar()
191     {
192         this(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
193     }
194
195     /**
196      * Constructs an <code>IslamicCalendar</code> based on the current time
197      * in the given time zone with the default <code>FORMAT</code> locale.
198      * @param zone the given time zone.
199      * @see Category#FORMAT
200      * @stable ICU 2.8
201      */
202     public IslamicCalendar(TimeZone zone)
203     {
204         this(zone, ULocale.getDefault(Category.FORMAT));
205     }
206
207     /**
208      * Constructs an <code>IslamicCalendar</code> based on the current time
209      * in the default time zone with the given locale.
210      *
211      * @param aLocale the given locale.
212      * @stable ICU 2.8
213      */
214     public IslamicCalendar(Locale aLocale)
215     {
216         this(TimeZone.getDefault(), aLocale);
217     }
218
219     /**
220      * Constructs an <code>IslamicCalendar</code> based on the current time
221      * in the default time zone with the given locale.
222      *
223      * @param locale the given ulocale.
224      * @stable ICU 3.2
225      */
226     public IslamicCalendar(ULocale locale)
227     {
228         this(TimeZone.getDefault(), locale);
229     }
230
231     /**
232      * Constructs an <code>IslamicCalendar</code> based on the current time
233      * in the given time zone with the given locale.
234      *
235      * @param zone the given time zone.
236      * @param aLocale the given locale.
237      * @stable ICU 2.8
238      */
239     public IslamicCalendar(TimeZone zone, Locale aLocale)
240     {
241         this(zone, ULocale.forLocale(aLocale));
242     }
243
244     /**
245      * Constructs an <code>IslamicCalendar</code> based on the current time
246      * in the given time zone with the given locale.
247      *
248      * @param zone the given time zone.
249      * @param locale the given ulocale.
250      * @stable ICU 3.2
251      */
252     public IslamicCalendar(TimeZone zone, ULocale locale)
253     {
254         super(zone, locale);
255         setCalcTypeForLocale(locale);
256         setTimeInMillis(System.currentTimeMillis());
257     }
258
259     /**
260      * Constructs an <code>IslamicCalendar</code> with the given date set
261      * in the default time zone with the default <code>FORMAT</code> locale.
262      *
263      * @param date      The date to which the new calendar is set.
264      * @see Category#FORMAT
265      * @stable ICU 2.8
266      */
267     public IslamicCalendar(Date date) {
268         super(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
269         this.setTime(date);
270     }
271
272     /**
273      * Constructs an <code>IslamicCalendar</code> with the given date set
274      * in the default time zone with the default <code>FORMAT</code> locale.
275      *
276      * @param year the value used to set the {@link #YEAR YEAR} time field in the calendar.
277      * @param month the value used to set the {@link #MONTH MONTH} time field in the calendar.
278      *              Note that the month value is 0-based. e.g., 0 for Muharram.
279      * @param date the value used to set the {@link #DATE DATE} time field in the calendar.
280      * @see Category#FORMAT
281      * @stable ICU 2.8
282      */
283     public IslamicCalendar(int year, int month, int date)
284     {
285         super(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
286         this.set(Calendar.YEAR, year);
287         this.set(Calendar.MONTH, month);
288         this.set(Calendar.DATE, date);
289     }
290
291     /**
292      * Constructs an <code>IslamicCalendar</code> with the given date
293      * and time set for the default time zone with the default <code>FORMAT</code> locale.
294      *
295      * @param year  the value used to set the {@link #YEAR YEAR} time field in the calendar.
296      * @param month the value used to set the {@link #MONTH MONTH} time field in the calendar.
297      *              Note that the month value is 0-based. e.g., 0 for Muharram.
298      * @param date  the value used to set the {@link #DATE DATE} time field in the calendar.
299      * @param hour  the value used to set the {@link #HOUR_OF_DAY HOUR_OF_DAY} time field
300      *              in the calendar.
301      * @param minute the value used to set the {@link #MINUTE MINUTE} time field
302      *              in the calendar.
303      * @param second the value used to set the {@link #SECOND SECOND} time field
304      *              in the calendar.
305      * @see Category#FORMAT
306      * @stable ICU 2.8
307      */
308     public IslamicCalendar(int year, int month, int date, int hour,
309                              int minute, int second)
310     {
311         super(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
312         this.set(Calendar.YEAR, year);
313         this.set(Calendar.MONTH, month);
314         this.set(Calendar.DATE, date);
315         this.set(Calendar.HOUR_OF_DAY, hour);
316         this.set(Calendar.MINUTE, minute);
317         this.set(Calendar.SECOND, second);
318     }
319
320     /**
321      * Determines whether this object uses the fixed-cycle Islamic civil calendar
322      * or an approximation of the religious, astronomical calendar.
323      *
324      * @param beCivil   <code>true</code> to use the civil calendar,
325      *                  <code>false</code> to use the astronomical calendar.
326      * @stable ICU 2.8
327      */
328     public void setCivil(boolean beCivil)
329     {
330         civil = beCivil;
331         
332         if (beCivil && cType != CalculationType.ISLAMIC_CIVIL) {
333             // The fields of the calendar will become invalid, because the calendar
334             // rules are different
335             long m = getTimeInMillis();
336             cType = CalculationType.ISLAMIC_CIVIL;
337             clear();
338             setTimeInMillis(m);
339         } else if(!beCivil && cType != CalculationType.ISLAMIC) {
340             // The fields of the calendar will become invalid, because the calendar
341             // rules are different
342             long m = getTimeInMillis();
343             cType = CalculationType.ISLAMIC;
344             clear();
345             setTimeInMillis(m);
346         }
347     }
348     
349     /**
350      * Returns <code>true</code> if this object is using the fixed-cycle civil
351      * calendar, or <code>false</code> if using the religious, astronomical
352      * calendar.
353      * @stable ICU 2.8
354      * 
355      */
356     public boolean isCivil() {
357         if(cType == CalculationType.ISLAMIC_CIVIL) {
358             return true;
359         }
360         return false;
361     }
362     
363     //-------------------------------------------------------------------------
364     // Minimum / Maximum access functions
365     //-------------------------------------------------------------------------
366
367     // Note: Current IslamicCalendar implementation does not work
368     // well with negative years.
369
370     private static final int LIMITS[][] = {
371         // Minimum  Greatest     Least   Maximum
372         //           Minimum   Maximum
373         {        0,        0,        0,        0}, // ERA
374         {        1,        1,  5000000,  5000000}, // YEAR
375         {        0,        0,       11,       11}, // MONTH
376         {        1,        1,       50,       51}, // WEEK_OF_YEAR
377         {/*                                   */}, // WEEK_OF_MONTH
378         {        1,        1,       29,       30}, // DAY_OF_MONTH
379         {        1,        1,      354,      355}, // DAY_OF_YEAR
380         {/*                                   */}, // DAY_OF_WEEK
381         {       -1,       -1,        5,        5}, // DAY_OF_WEEK_IN_MONTH
382         {/*                                   */}, // AM_PM
383         {/*                                   */}, // HOUR
384         {/*                                   */}, // HOUR_OF_DAY
385         {/*                                   */}, // MINUTE
386         {/*                                   */}, // SECOND
387         {/*                                   */}, // MILLISECOND
388         {/*                                   */}, // ZONE_OFFSET
389         {/*                                   */}, // DST_OFFSET
390         {        1,        1,  5000000,  5000000}, // YEAR_WOY
391         {/*                                   */}, // DOW_LOCAL
392         {        1,        1,  5000000,  5000000}, // EXTENDED_YEAR
393         {/*                                   */}, // JULIAN_DAY
394         {/*                                   */}, // MILLISECONDS_IN_DAY
395     };
396     
397     /*
398      * bit map array where a bit turned on represents a month with 30 days. 
399      */
400     private static final int[] UMALQURA_MONTHLENGTH = {
401         //* 1318 -1322 */ "0101 0111 0100", "1001 0111 0110", "0100 1011 0111", "0010 0101 0111", "0101 0010 1011",
402                                0x0574,           0x0975,           0x06A7,           0x0257,           0x052B,
403         //* 1323 -1327 */ "0110 1001 0101", "0110 1100 1010", "1010 1101 0101", "0101 0101 1011", "0010 0101 1101",
404                                0x0695,           0x06CA,           0x0AD5,           0x055B,           0x025B,
405         //* 1328 -1332 */ "1001 0010 1101", "1100 1001 0101", "1101 0100 1010", "1110 1010 0101", "0110 1101 0010",
406                                0x092D,           0x0C95,           0x0D4A,           0x0E5B,           0x025B,
407         //* 1333 -1337 */ "1010 1101 0101", "0101 0101 1010", "1010 1010 1011", "0100 0100 1011", "0110 1010 0101",
408                                0x0AD5,           0x055A,           0x0AAB,           0x044B,           0x06A5,
409         //* 1338 -1342 */ "0111 0101 0010", "1011 1010 1001", "0011 0111 0100", "1010 1011 0110", "0101 0101 0110",
410                                0x0752,           0x0BA9,           0x0374,           0x0AB6,           0x0556,
411         //* 1343 -1347 */ "1010 1010 1010", "1101 0101 0010", "1101 1010 1001", "0101 1101 0100", "1010 1110 1010",
412                                0x0AAA,           0x0D52,           0x0DA9,           0x05D4,           0x0AEA,
413         //* 1348 -1352 */ "0100 1101 1101", "0010 0110 1110", "1001 0010 1110", "1010 1010 0110", "1101 0101 0100",
414                                0x04DD,           0x026E,           0x092E,           0x0AA6,           0x0D54,
415         //* 1353 -1357 */ "0101 1010 1010", "0101 1011 0101", "0010 1011 0100", "1001 0011 0111", "0100 1001 1011",
416                                0x05AA,           0x05B5,           0x02B4,           0x0937,           0x049B,
417         //* 1358 -1362 */ "1010 0100 1011", "1011 0010 0101", "1011 0101 0100", "1011 0110 1010", "0101 0110 1101",
418                                0x0A4B,           0x0B25,           0x0B54,           0x0B6A,           0x056D,
419         //* 1363 -1367 */ "0100 1010 1101", "1010 0101 0101", "1101 0010 0101", "1110 1001 0010", "1110 1100 1001",
420                                0x04AD,           0x0A55,           0x0D25,           0x0E92,           0x0EC9,
421         //* 1368 -1372 */ "0110 1101 0100", "1010 1110 1010", "0101 0110 1011", "0100 1010 1011", "0110 1000 0101",
422                                0x06D4,           0x0ADA,           0x056B,           0x04AB,           0x0685,
423         //* 1373 -1377 */ "1011 0100 1001", "1011 1010 0100", "1011 1011 0010", "0101 1011 0101", "0010 1011 1010",
424                                0x0B49,           0x0BA4,           0x0BB2,           0x05B5,           0x02BA,
425         //* 1378 -1382 */ "1001 0101 1011", "0100 1010 1011", "0101 0101 0101", "0110 1011 0010", "0110 1101 1001",
426                                0x095B,           0x04AB,           0x0555,           0x06B2,           0x06D9,
427         //* 1383 -1387 */ "0010 1110 1100", "1001 0110 1110", "0100 1010 1110", "1010 0101 0110", "1101 0010 1010",
428                                0x02EC,           0x096E,           0x04AE,           0x0A56,           0x0D2A,
429         //* 1388 -1392 */ "1101 0101 0101", "0101 1010 1010", "1010 1011 0101", "0100 1011 1011", "0000 0101 1011",
430                                0x0D55,           0x05AA,           0x0AB5,           0x04BB,           0x005B,
431         //* 1393 -1397 */ "1001 0010 1011", "1010 1001 0101", "0011 0100 1010", "1011 1010 0101", "0101 1010 1010",
432                                0x092B,           0x0A95,           0x034A,           0x0BA5,           0x05AA,
433         //* 1398 -1402 */ "1010 1011 0101", "0101 0101 0110", "1010 1001 0110", "1101 0100 1010", "1110 1010 0101",
434                                0x0AB5,           0x0556,           0x0A96,           0x0B4A,           0x0EA5,
435         //* 1403 -1407 */ "0111 0101 0010", "0110 1110 1001", "0011 0110 1010", "1010 1010 1101", "0101 0101 0101",
436                                0x0752,           0x06E9,           0x036A,           0x0AAD,           0x0555,
437         //* 1408 -1412 */ "1010 1010 0101", "1011 0101 0010", "1011 1010 1001", "0101 1011 0100", "1001 1011 1010",
438                                0x0AA5,           0x0B52,           0x0BA9,           0x05B4,           0x09BA,
439         //* 1413 -1417 */ "0100 1101 1011", "0010 0101 1101", "0101 0010 1101", "1010 1010 0101", "1010 1101 0100",
440                                0x04DB,           0x025D,           0x052D,           0x0AA5,           0x0AD4,
441         //* 1418 -1422 */ "1010 1110 1010", "0101 0110 1101", "0100 1011 1101", "0010 0011 1101", "1001 0001 1101",
442                                0x0AEA,           0x056D,           0x04BD,           0x023D,           0x091D,
443         //* 1423 -1427 */ "1010 1001 0101", "1011 0100 1010", "1011 0101 1010", "0101 0110 1101", "0010 1011 0110",
444                                0x0A95,           0x0B4A,           0x0B5A,           0x056D,           0x02B6,
445         //* 1428 -1432 */ "1001 0011 1011", "0100 1001 1011", "0110 0101 0101", "0110 1010 1001", "0111 0101 0100",
446                                0x093B,           0x049B,           0x0655,           0x06A9,           0x0754,
447         //* 1433 -1437 */ "1011 0110 1010", "0101 0110 1100", "1010 1010 1101", "0101 0101 0101", "1011 0010 1001",
448                                0x0B6A,           0x056C,           0x0AAD,           0x0555,           0x0B29,
449         //* 1438 -1442 */ "1011 1001 0010", "1011 1010 1001", "0101 1101 0100", "1010 1101 1010", "0101 0101 1010",
450                                0x0B92,           0x0BA9,           0x05D4,           0x0ADA,           0x055A,
451         //* 1443 -1447 */ "1010 1010 1011", "0101 1001 0101", "0111 0100 1001", "0111 0110 0100", "1011 1010 1010",
452                                0x0AAB,           0x0595,           0x0749,           0x0764,           0x0BAA,
453         //* 1448 -1452 */ "0101 1011 0101", "0010 1011 0110", "1010 0101 0110", "1110 0100 1101", "1011 0010 0101",
454                                0x05B5,           0x02B6,           0x0A56,           0x0E4D,           0x0B25,
455         //* 1453 -1457 */ "1011 0101 0010", "1011 0110 1010", "0101 1010 1101", "0010 1010 1110", "1001 0010 1111",
456                                0x0B52,           0x0B6A,           0x05AD,           0x02AE,           0x092F,
457         //* 1458 -1462 */ "0100 1001 0111", "0110 0100 1011", "0110 1010 0101", "0110 1010 1100", "1010 1101 0110",
458                                0x0497,           0x064B,           0x06A5,           0x06AC,           0x0AD6,
459         //* 1463 -1467 */ "0101 0101 1101", "0100 1001 1101", "1010 0100 1101", "1101 0001 0110", "1101 1001 0101",
460                                0x055D,           0x049D,           0x0A4D,           0x0D16,           0x0D95,
461         //* 1468 -1472 */ "0101 1010 1010", "0101 1011 0101", "0010 1001 1010", "1001 0101 1011", "0100 1010 1100",
462                                0x05AA,           0x05B5,           0x029A,           0x095B,           0x04AC,
463         //* 1473 -1477 */ "0101 1001 0101", "0110 1100 1010", "0110 1110 0100", "1010 1110 1010", "0100 1111 0101",
464                                0x0595,           0x06CA,           0x06E4,           0x0AEA,           0x04F5,
465         //* 1478 -1480 */ "0010 1011 0110", "1001 0101 0110", "1010 1010 1010"
466                                0x02B6,           0x0956,           0x0AAA
467     };
468
469     private static final int UMALQURA_YEAR_START = 1318;
470     private static final int UMALQURA_YEAR_END = 1480;
471
472
473     /**
474      * @stable ICU 2.8
475      */
476     protected int handleGetLimit(int field, int limitType) {
477         return LIMITS[field][limitType];
478     }
479
480     //-------------------------------------------------------------------------
481     // Assorted calculation utilities
482     //
483
484 // Unused code - Alan 2003-05
485 //    /**
486 //     * Find the day of the week for a given day
487 //     *
488 //     * @param day   The # of days since the start of the Islamic calendar.
489 //     */
490 //    // private and uncalled, perhaps not used yet?
491 //    private static final int absoluteDayToDayOfWeek(long day)
492 //    {
493 //        // Calculate the day of the week.
494 //        // This relies on the fact that the epoch was a Thursday.
495 //        int dayOfWeek = (int)(day + THURSDAY) % 7 + SUNDAY;
496 //        if (dayOfWeek < 0) {
497 //            dayOfWeek += 7;
498 //        }
499 //        return dayOfWeek;
500 //    }
501
502     /**
503      * Determine whether a year is a leap year in the Islamic civil calendar
504      */
505     private final static boolean civilLeapYear(int year)
506     {
507         return (14 + 11 * year) % 30 < 11;
508     }
509     
510     /**
511      * Return the day # on which the given year starts.  Days are counted
512      * from the Hijri epoch, origin 0.
513      */
514     private long yearStart(int year) {
515         long ys = 0;
516         if (cType == CalculationType.ISLAMIC_CIVIL
517                 || cType == CalculationType.ISLAMIC_TBLA
518                 || (cType == CalculationType.ISLAMIC_UMALQURA && year < UMALQURA_YEAR_START )) {
519              ys = (year-1)*354 + (long)Math.floor((3+11*year)/30.0);
520         } else if(cType == CalculationType.ISLAMIC) {
521              ys = trueMonthStart(12*(year-1));
522         } else if(cType == CalculationType.ISLAMIC_UMALQURA){
523              ys = yearStart(UMALQURA_YEAR_START -1);  
524              ys += handleGetYearLength(UMALQURA_YEAR_START -1);
525              for(int i=UMALQURA_YEAR_START; i< year; i++) {
526                 ys+= handleGetYearLength(i);
527             }
528         }
529         return ys;
530     }
531
532     /**
533      * Return the day # on which the given month starts.  Days are counted
534      * from the Hijri epoch, origin 0.
535      *
536      * @param year  The hijri year
537      * @param month  The hijri month, 0-based
538      */
539     private long monthStart(int year, int month) {
540         // Normalize year/month in case month is outside the normal bounds, which may occur
541         // in the case of an add operation
542         int realYear = year + month / 12;
543         int realMonth = month % 12;
544         long ms = 0;
545         if (cType == CalculationType.ISLAMIC_CIVIL
546                 || cType == CalculationType.ISLAMIC_TBLA
547                 || (cType == CalculationType.ISLAMIC_UMALQURA && year < UMALQURA_YEAR_START )) {
548             ms = (long)Math.ceil(29.5*realMonth)
549                     + (realYear-1)*354 + (long)Math.floor((3+11*realYear)/30.0);
550         } else if(cType == CalculationType.ISLAMIC) {
551             ms = trueMonthStart(12*(realYear-1) + realMonth);
552         } else if(cType == CalculationType.ISLAMIC_UMALQURA) {
553             ms = yearStart(year);
554             for(int i=0; i< month; i++) {
555                 ms+= handleGetMonthLength(year, i);
556             }
557         }
558
559         return ms;
560     }
561     
562     /**
563      * Find the day number on which a particular month of the true/lunar
564      * Islamic calendar starts.
565      *
566      * @param month The month in question, origin 0 from the Hijri epoch
567      *
568      * @return The day number on which the given month starts.
569      */
570     private static final long trueMonthStart(long month)
571     {
572         long start = cache.get(month);
573
574         if (start == CalendarCache.EMPTY)
575         {
576             // Make a guess at when the month started, using the average length
577             long origin = HIJRA_MILLIS 
578                         + (long)Math.floor(month * CalendarAstronomer.SYNODIC_MONTH) * ONE_DAY;
579
580             double age = moonAge(origin);
581
582             if (moonAge(origin) >= 0) {
583                 // The month has already started
584                 do {
585                     origin -= ONE_DAY;
586                     age = moonAge(origin);
587                 } while (age >= 0);
588             }
589             else {
590                 // Preceding month has not ended yet.
591                 do {
592                     origin += ONE_DAY;
593                     age = moonAge(origin);
594                 } while (age < 0);
595             }
596
597             start = (origin - HIJRA_MILLIS) / ONE_DAY + 1;
598             
599             cache.put(month, start);
600         }
601         return start;
602     }
603
604     /**
605      * Return the "age" of the moon at the given time; this is the difference
606      * in ecliptic latitude between the moon and the sun.  This method simply
607      * calls CalendarAstronomer.moonAge, converts to degrees, 
608      * and adjusts the resultto be in the range [-180, 180].
609      *
610      * @param time  The time at which the moon's age is desired,
611      *              in millis since 1/1/1970.
612      */
613     static final double moonAge(long time)
614     {
615         double age = 0;
616         
617         synchronized(astro) {
618             astro.setTime(time);
619             age = astro.getMoonAge();
620         }
621         // Convert to degrees and normalize...
622         age = age * 180 / Math.PI;
623         if (age > 180) {
624             age = age - 360;
625         }
626
627         return age;
628     }
629
630     //-------------------------------------------------------------------------
631     // Internal data....
632     //
633     
634     // And an Astronomer object for the moon age calculations
635     private static CalendarAstronomer astro = new CalendarAstronomer();
636     
637     private static CalendarCache cache = new CalendarCache();
638     
639     /**
640      * <code>true</code> if this object uses the fixed-cycle Islamic civil calendar,
641      * and <code>false</code> if it approximates the true religious calendar using
642      * astronomical calculations for the time of the new moon.
643      *
644      * @serial
645      */
646     private boolean civil = true;
647     
648     /**
649      * determines the type of calculation to use for this instance
650      * 
651      * @serial
652      * @draft ICU 52
653      * @provisional This API might change or be removed in a future release.
654      */
655     private CalculationType cType = CalculationType.ISLAMIC_CIVIL;
656
657     //----------------------------------------------------------------------
658     // Calendar framework
659     //----------------------------------------------------------------------
660
661     /**
662      * Return the length (in days) of the given month.
663      *
664      * @param extendedYear  The hijri year
665      * @param month The hijri month, 0-based
666      * @stable ICU 2.8
667      */
668     protected int handleGetMonthLength(int extendedYear, int month) {
669
670         int length = 0;
671         
672         if (cType == CalculationType.ISLAMIC_CIVIL
673                 || cType == CalculationType.ISLAMIC_TBLA
674                 || (cType == CalculationType.ISLAMIC_UMALQURA && (extendedYear < UMALQURA_YEAR_START  || extendedYear > UMALQURA_YEAR_END) )) {
675             length = 29 + (month+1) % 2;
676             if (month == DHU_AL_HIJJAH && civilLeapYear(extendedYear)) {
677                 length++;
678             } 
679         } else if (cType == CalculationType.ISLAMIC) {
680             month = 12*(extendedYear-1) + month;
681             length = (int)( trueMonthStart(month+1) - trueMonthStart(month) );
682         }else if (cType == CalculationType.ISLAMIC_UMALQURA){            
683             int idx = (extendedYear - UMALQURA_YEAR_START);     // calculate year offset into bit map array
684             int mask = (0x01 << (11 - month));                  // set mask for bit corresponding to month            
685             if((UMALQURA_MONTHLENGTH[idx] & mask) == 0 )    
686                 length = 29;
687             else
688                 length = 30;
689         }
690         return length;
691     }
692
693     /**
694      * Return the number of days in the given Islamic year
695      * @stable ICU 2.8
696      */
697     protected int handleGetYearLength(int extendedYear) {
698         int length =0; 
699         if (cType == CalculationType.ISLAMIC_CIVIL
700                 || cType == CalculationType.ISLAMIC_TBLA
701                 || (cType == CalculationType.ISLAMIC_UMALQURA && (extendedYear < UMALQURA_YEAR_START  || extendedYear > UMALQURA_YEAR_END) )) {
702             length =  354 + (civilLeapYear(extendedYear) ? 1 : 0);
703         } else if (cType == CalculationType.ISLAMIC) {
704             int month = 12*(extendedYear-1);
705             length =  (int)(trueMonthStart(month + 12) - trueMonthStart(month));
706         } else if (cType == CalculationType.ISLAMIC_UMALQURA) {
707             for(int i=0; i<12; i++)
708                 length += handleGetMonthLength(extendedYear, i);
709         }
710
711         return length;
712     }
713     
714     //-------------------------------------------------------------------------
715     // Functions for converting from field values to milliseconds....
716     //-------------------------------------------------------------------------
717
718     // Return JD of start of given month/year
719     /**
720      * @stable ICU 2.8
721      */
722     protected int handleComputeMonthStart(int eyear, int month, boolean useMonth) {
723         return (int) monthStart(eyear, month) + 1948439;
724     }    
725
726     //-------------------------------------------------------------------------
727     // Functions for converting from milliseconds to field values
728     //-------------------------------------------------------------------------
729
730     /**
731      * @stable ICU 2.8
732      */
733     protected int handleGetExtendedYear() {
734         int year;
735         if (newerField(EXTENDED_YEAR, YEAR) == EXTENDED_YEAR) {
736             year = internalGet(EXTENDED_YEAR, 1); // Default to year 1
737         } else {
738             year = internalGet(YEAR, 1); // Default to year 1
739         }
740         return year;
741     }
742
743     /**
744      * Override Calendar to compute several fields specific to the Islamic
745      * calendar system.  These are:
746      *
747      * <ul><li>ERA
748      * <li>YEAR
749      * <li>MONTH
750      * <li>DAY_OF_MONTH
751      * <li>DAY_OF_YEAR
752      * <li>EXTENDED_YEAR</ul>
753      * 
754      * The DAY_OF_WEEK and DOW_LOCAL fields are already set when this
755      * method is called. The getGregorianXxx() methods return Gregorian
756      * calendar equivalents for the given Julian day.
757      * @stable ICU 2.8
758      */
759     protected void handleComputeFields(int julianDay) {
760         int year =0, month=0, dayOfMonth=0, dayOfYear=0;
761         long monthStart;
762         long days = julianDay - CIVIL_EPOC;
763
764         if (cType == CalculationType.ISLAMIC_CIVIL || cType == CalculationType.ISLAMIC_TBLA) {
765             if (cType == CalculationType.ISLAMIC_TBLA) {
766                 days = julianDay - ASTRONOMICAL_EPOC;
767             }
768             // Use the civil calendar approximation, which is just arithmetic
769             year  = (int)Math.floor( (30 * days + 10646) / 10631.0 );
770             month = (int)Math.ceil((days - 29 - yearStart(year)) / 29.5 );
771             month = Math.min(month, 11);
772         } else if (cType == CalculationType.ISLAMIC){
773             // Guess at the number of elapsed full months since the epoch
774             int months = (int)Math.floor(days / CalendarAstronomer.SYNODIC_MONTH);
775
776             monthStart = (long)Math.floor(months * CalendarAstronomer.SYNODIC_MONTH - 1);
777
778             if ( days - monthStart >= 25 && moonAge(internalGetTimeInMillis()) > 0) {
779                 // If we're near the end of the month, assume next month and search backwards
780                 months++;
781             }
782
783             // Find out the last time that the new moon was actually visible at this longitude
784             // This returns midnight the night that the moon was visible at sunset.
785             while ((monthStart = trueMonthStart(months)) > days) {
786                 // If it was after the date in question, back up a month and try again
787                 months--;
788             }
789
790             year = months / 12 + 1;
791             month = months % 12;
792         } else if (cType == CalculationType.ISLAMIC_UMALQURA) {
793             long umalquraStartdays = yearStart(UMALQURA_YEAR_START);
794             if( days < umalquraStartdays) {
795                 // Use Civil calculation
796                 year  = (int)Math.floor( (30 * days + 10646) / 10631.0 );
797                 month = (int)Math.ceil((days - 29 - yearStart(year)) / 29.5 );
798                 month = Math.min(month, 11);
799             } else {
800                 int y =UMALQURA_YEAR_START-1, m =0;
801                 long d = 1;
802                 while(d > 0) { 
803                     y++; 
804                     d = days - yearStart(y) +1;
805                     if(d == handleGetYearLength(y)) {
806                         m=11;
807                         break;
808                     } else if(d < handleGetYearLength(y) ) {
809                         int monthLen = handleGetMonthLength(y, m); 
810                         m=0;
811                         while(d > monthLen) {
812                             d -= monthLen;
813                             m++;
814                             monthLen = handleGetMonthLength(y, m);
815                         }
816                         break;
817                     }
818                 }
819                 year = y;
820                 month = m;
821             }
822         }
823
824        
825         dayOfMonth = (int)(days - monthStart(year, month)) + 1;
826
827         // Now figure out the day of the year.
828         dayOfYear = (int)(days - monthStart(year, 0) + 1);
829         
830
831         internalSet(ERA, 0);
832         internalSet(YEAR, year);
833         internalSet(EXTENDED_YEAR, year);
834         internalSet(MONTH, month);
835         internalSet(DAY_OF_MONTH, dayOfMonth);
836         internalSet(DAY_OF_YEAR, dayOfYear);       
837     }    
838     
839     /**
840      *  enumeration of available calendar calculation types
841      *  
842      * @draft ICU 52
843      * @provisional This API might change or be removed in a future release.
844      */
845     public enum CalculationType {
846         /**
847          * Religious calendar (atronomical simulation)
848          * @draft ICU 52
849          * @provisional This API might change or be removed in a future release.
850          */
851         ISLAMIC             ("islamic"),
852         /**
853          * Tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29]) algorithm
854          * with civil (Friday) epoch.
855          * @draft ICU 52
856          * @provisional This API might change or be removed in a future release.
857          */
858         ISLAMIC_CIVIL       ("islamic-civil"),
859         /**
860          * Umm al-Qura calendar
861          * @draft ICU 52
862          * @provisional This API might change or be removed in a future release.
863          */
864         ISLAMIC_UMALQURA    ("islamic-umalqura"),
865         /**
866          * Tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29]) algorithm
867          * with astronomical (Thursday) epoch.
868          * @draft ICU 52
869          * @provisional This API might change or be removed in a future release.
870          */
871         ISLAMIC_TBLA        ("islamic-tbla");
872
873         private String bcpType;
874
875         CalculationType(String bcpType) {
876             this.bcpType = bcpType;
877         }
878
879         String bcpType() {
880             return bcpType;
881         }
882     };
883     
884     /**
885      * sets the calculation type for this calendar.
886      * 
887      * @draft ICU 52
888      * @provisional This API might change or be removed in a future release.
889      */
890     // TODO: We should change the method name to setCalculationType, because
891     // corresponding getter (not yet available) will collide with String getType().
892     // See ticket#10426.
893     public void setType(CalculationType type) {
894         cType = type;
895         
896         // ensure civil property is up-to-date
897         if(cType == CalculationType.ISLAMIC_CIVIL) 
898             civil = true;
899         else
900             civil = false;
901     }
902
903     /**
904      * set type based on locale
905      */
906     private void setCalcTypeForLocale(ULocale locale) {
907         String localeCalType = CalendarUtil.getCalendarType(locale);
908         if("islamic-civil".equals(localeCalType)) 
909             setType(CalculationType.ISLAMIC_CIVIL);
910         else if("islamic-umalqura".equals(localeCalType)) 
911             setType(CalculationType.ISLAMIC_UMALQURA);
912         else if("islamic-tbla".equals(localeCalType)) 
913             setType(CalculationType.ISLAMIC_TBLA);
914         else if(localeCalType.startsWith("islamic"))
915             setType(CalculationType.ISLAMIC);       // needs to be last so it's always the default if it's islamic-something-unhandled  
916         else 
917             setType(CalculationType.ISLAMIC_CIVIL); // default for any non-islamic calendar locale
918     }
919
920     
921     /**
922      * {@inheritDoc}
923      * @stable ICU 3.8
924      */
925     public String getType() {
926         if (cType == null) {
927             // TODO: getType() is called during Islamic calendar
928             // construction and might be null at that point. We should
929             // check the initialization sequence. See ticket#10425.
930             return "islamic";
931         }
932         return cType.bcpType();
933     }
934
935     private void readObject(ObjectInputStream in) throws IOException,ClassNotFoundException 
936     {
937             in.defaultReadObject();
938             
939             if(cType != CalculationType.ISLAMIC_CIVIL)
940                 return;     // we've serialized something new, nothing else to do
941             
942             // new calculation type is civil (default) but civil is false. This will only happen
943             // when deserializing a non-civil calender so need to adjust new CalculationType to match 
944             // serialized form
945             if(!civil)
946                 cType = CalculationType.ISLAMIC;  
947     }
948     
949     /*
950     private static CalendarFactory factory;
951     public static CalendarFactory factory() {
952         if (factory == null) {
953             factory = new CalendarFactory() {
954                 public Calendar create(TimeZone tz, ULocale loc) {
955                     return new IslamicCalendar(tz, loc);
956                 }
957
958                 public String factoryName() {
959                     return "Islamic";
960                 }
961             };
962         }
963         return factory;
964     }
965     */
966 }