1 | package net.sourceforge.calendardate; |
2 | import java.util.Calendar; |
3 | import java.util.GregorianCalendar; |
4 | |
5 | import junit.framework.TestCase; |
6 | |
7 | |
8 | public class ManualCalculationTestCase extends TestCase { |
9 | |
10 | |
11 | public void testDaysUntil() { |
12 | GregorianCalendar startDate = new GregorianCalendar(2000, 0, 1); |
13 | for (int day = -(366 * 400); day < (366 * 400); day++) { |
14 | GregorianCalendar endDate = new GregorianCalendar(2000, 0, 1 + day); |
15 | assertEquals(endDate.getTime().toString(), day, DayCounter.daysUntil(startDate, endDate)); |
16 | } |
17 | } |
18 | |
19 | |
20 | } |
21 | |
22 | class DayCounter { |
23 | public static int daysUntil(Calendar fromDate, Calendar toDate) { |
24 | return daysSinceEpoch(toDate) - daysSinceEpoch(fromDate); |
25 | } |
26 | |
27 | public static int daysSinceEpoch(Calendar day) { |
28 | int year = day.get(Calendar.YEAR); |
29 | int month = day.get(Calendar.MONTH); |
30 | int daysThisYear = cumulDaysToMonth[month] + day.get(Calendar.DAY_OF_MONTH) - 1; |
31 | if ((month > 1) && isLeapYear(year)) { |
32 | daysThisYear++; |
33 | } |
34 | |
35 | return daysToYear(year) + daysThisYear; |
36 | } |
37 | |
38 | public static boolean isLeapYear(int year) { |
39 | return (year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0)); |
40 | } |
41 | |
42 | static int daysToYear(int year) { |
43 | return (365 * year) + numLeapsToYear(year); |
44 | } |
45 | |
46 | static int numLeapsToYear(int year) { |
47 | int num4y = (year - 1) / 4; |
48 | int num100y = (year - 1) / 100; |
49 | int num400y = (year - 1) / 400; |
50 | return num4y - num100y + num400y; |
51 | } |
52 | |
53 | private static final int[] cumulDaysToMonth = { 0, 31, 59, 90, 120, 151, |
54 | 181, 212, 243, 273, 304, 334 }; |
55 | } |