Date Range Problem

♠ Posted by GeekyFry in ,,,, at 6:52 AM
Given specifications for two dates, find the number of days (inclusive) in the range defined by the two dates.

Constraints:
In solving this problem, you cannot use any JDK or external classes (such as java.util.Date or java.util.Calendar or System.DateTime) for computing dates. However, you may use other core JDK/.NET classes, such as the java.io classes required to perform I/O.
The solution must work for all dates in the range 1/1/1901 through 12/31/2999, inclusive.
Note that the result should be the number of days in the range, including the endpoint dates. For example, there are 5 days in the range bounded by 3/15/2004 and 3/19/2004.
Sample Input: 
3, 4, 1988, 3, 30, 19887, 
12, 1984, 12, 20, 1984
1, 3, 1989, 3, 8, 1983
Sample Output:
27
162
2129
Possible Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class DateUtil {
 
  public static void main(String[] args) {
   {
     MyDate d1 = new MyDate(4, 3, 1988);
     MyDate d2 = new MyDate(30, 3, 1988);
     int ans = d2.noOfDaysWith(d1);
     System.out.println(" ans " + ans);
   }
 
   {
     MyDate d1 = new MyDate(12, 7, 1984);
     MyDate d2 = new MyDate(20, 12, 1984);
     int ans = d2.noOfDaysWith(d1);
     System.out.println(" ans2 " + ans);
   }
 
   {
     MyDate d1 = new MyDate(3, 1, 1989);
     MyDate d2 = new MyDate(8, 3, 1983);
     int ans = d1.noOfDaysWith(d2);
     System.out.println(" ans3 " + ans);
   }
 
   MyDate today = new MyDate(6, 3, 2012);
   MyDate myBirthDay = new MyDate(6, 8, 1982);
   MyDate asBirthDay = new MyDate(28, 3, 2011);
 
   System.out.println(" today is " + today.getAbsDay());
   System.out.println(" My Age " + today.noOfDaysWith(myBirthDay));
   System.out.println(" AS Age " + today.noOfDaysWith(asBirthDay));
 }
 
 public static class MyDate {
   int monthDays[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
   final public int day, month, year;
   final public boolean isLeap;
 
   public MyDate(int day, int month, int year) {
     super();
     this.day = day;
     this.month = month;
     this.year = year;
     this.isLeap = year % 4 == 0;
 
     if (isLeap) {
       monthDays[1] = 29;
     }
   }
 
   public int noOfDaysWith(MyDate myDate) {
     return getAbsDay() - myDate.getAbsDay() + 1;
   }
 
   public int getAbsDay() {
     if (year < 1901) {
       throw new IllegalArgumentException();
     }
 
     int absDays = 0;
     int dYear = year;
     int noOfLeapYears = dYear / 4;
 
     absDays = dYear * 365 + noOfLeapYears;
     // add months
     for (int i = 0; i < month; i++) {
       absDays += monthDays[i];
     }
     absDays += day;
     return absDays;
   }
 }
}

0 comments:

Post a Comment