Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1170
  • Last Modified:

java.sql.date calculations

hi,
  i wanted to know how do you calculate the number of days between two dates in java ? i get both the dates from the database. i guess there are many issues like leap year and Febuary having diff no of months ..etc.

 a sample code with just be great.

 badly in need of assistance

 Thanks
0
pravin_tiwari
Asked:
pravin_tiwari
1 Solution
 
superschlonzCommented:
Date d1, d2;

int days =(int)(  (d1.getTime()-d2.getTime()) / 86400000 );

getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT.
86400000 == 24 * 60 * 60 * 1000
0
 
venkat2000120699Commented:
The problem with the above sample is it doesn't work for dates before the year 1970.  

Here is the code with traditional logic, which doesn't use any library methods provided by java.  It works for all dates.

U can use which ever solution u want depending on your requirement.

public class DiffDates {

     public boolean chkleap(int year) {
          boolean isLeap = false;
          if ((year % 4) == 0) {
              isLeap = true;
          }
         
          if (((year % 100) == 0) && ((year % 400) != 0)) {
              isLeap = false;
          }
         
          return isLeap;
     }//end of chkleap()
     
        public DiffDates() {
            int M[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
           
            int i=0,j=0,k=0;
            long count=0;
           
            int d1=13, d2=14;
            int m1=6,m2=6;
            int y1=1975,y2=2001;
           
            /*
              To find difference between 13 th June 1975 and 14 th June 2001.
              d1 = 13, m1 = 6, y1 = 1975
              d2 = 14, m2 = 6, y2 = 2001
            */
           
            if (y1!=y2) {
             for (i=y1;i<y2;i++) {
                 if (chkleap(i)) count+=366;
                 else count+=365;
             }
            }
           
            if (chkleap(y1)) M[2]=29;
           
            k=d1;
     
            if (m1!=1) {
             for (i=1;i<m1;i++)
                 k+=M[i];
            }
     
            if (chkleap(y2)) M[2]=29;
            else M[2]=28;
           
            j=d2;
     
            if (m2!=1) {
             for (i=1;i<m2;i++)
                 j+=M[i];
            }
           
            count = count + (j - k);
     
            System.out.println("The difference between two given dates is: " + count + " Days");
        }//end of constructor
       
        public static void main(String args[]) {
            new DiffDates();
        }//end of main()
}//end of class DiffDates
0
 
venkat2000120699Commented:
The problem with the above sample is it doesn't work for dates before the year 1970.  

Here is the code with traditional logic, which doesn't use any library methods provided by java.  It works for all dates.

U can use which ever solution u want depending on your requirement.

public class DiffDates {

     public boolean chkleap(int year) {
          boolean isLeap = false;
          if ((year % 4) == 0) {
              isLeap = true;
          }
         
          if (((year % 100) == 0) && ((year % 400) != 0)) {
              isLeap = false;
          }
         
          return isLeap;
     }//end of chkleap()
     
        public DiffDates() {
            int M[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
           
            int i=0,j=0,k=0;
            long count=0;
           
            int d1=13, d2=14;
            int m1=6,m2=6;
            int y1=1975,y2=2001;
           
            /*
              To find difference between 13 th June 1975 and 14 th June 2001.
              d1 = 13, m1 = 6, y1 = 1975
              d2 = 14, m2 = 6, y2 = 2001
            */
           
            if (y1!=y2) {
             for (i=y1;i<y2;i++) {
                 if (chkleap(i)) count+=366;
                 else count+=365;
             }
            }
           
            if (chkleap(y1)) M[2]=29;
           
            k=d1;
     
            if (m1!=1) {
             for (i=1;i<m1;i++)
                 k+=M[i];
            }
     
            if (chkleap(y2)) M[2]=29;
            else M[2]=28;
           
            j=d2;
     
            if (m2!=1) {
             for (i=1;i<m2;i++)
                 j+=M[i];
            }
           
            count = count + (j - k);
     
            System.out.println("The difference between two given dates is: " + count + " Days");
        }//end of constructor
       
        public static void main(String args[]) {
            new DiffDates();
        }//end of main()
}//end of class DiffDates
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
venkat2000120699Commented:
Sorry for posting the same answer twice.  But it is not my mistake.  I have just pressed the refresh button of the browser.

Coming back to the above solution, u have to make sure that first date(d1, m1, y1) comes before the second date(d2, m2, y2).  To do so, u can use compareTo() method in java.util.Date class (or) u can write your own logic.
0
 
SendohCommented:
hi there....
i got another example here...
hope it helps...:)

first of all, conver the 2 date(String) to Calendar obj...
then

int DayDiff(Calendar y,Calendar z)
{
     int counter=0;

     while(true)
     {
          Holiday a = new Holiday(y);

          if (y.get(Calendar.DATE)==z.get(Calendar.DATE) &&
               y.get(Calendar.MONTH)==z.get(Calendar.MONTH) &&
               y.get(Calendar.YEAR)==z.get(Calendar.YEAR))
          {
               break;
          }

          counter++;

          y.roll(Calendar.DATE,true);
          if (y.get(Calendar.DATE)==1)
          {
               y.roll(Calendar.MONTH,true);
               if (y.get(Calendar.MONTH)==1)
               {
                    y.roll(Calendar.YEAR,true);
               }
          }
     }
     return counter;
}

with this codes, u can even add in ur own requirement like exclude sunday or public holiday...:P

0
 
superschlonzCommented:
Hi vertical2000

Why do you think my versin doesn't work before 1970 ???

getTime() should return negative values and all should work.

I think the only thing it doesn't do properly are these leap seconds.
0
 
MoondancerCommented:
ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101 or Netminder will return to finalize these if still open in seven days.  Please post closing recommendations before that time.

Question(s) below appears to have been abandoned. Your options are:
 
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> YOU CANNOT DELETE A QUESTION with comments; special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click this link for Help Desk, Guidelines/Member Agreement and the Question/Answer process.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Click you Member Profile to view your question history and please keep them updated. If you are a KnowledgePro user, use the Power Search option to find them.  

Questions which are LOCKED with a Proposed Answer but do not help you, should be rejected with comments added.  When you grade the question less than an A, please comment as to why.  This helps all involved, as well as others who may access this item in the future.  PLEASE DO NOT AWARD POINTS TO ME.

To view your open questions, please click the following link(s) and keep them all current with updates.
http://www.experts-exchange.com/questions/Q.11583218.html
http://www.experts-exchange.com/questions/Q.20110298.html
http://www.experts-exchange.com/questions/Q.20135782.html
http://www.experts-exchange.com/questions/Q.20135845.html
http://www.experts-exchange.com/questions/Q.20137406.html
http://www.experts-exchange.com/questions/Q.20155091.html
http://www.experts-exchange.com/questions/Q.20155730.html
http://www.experts-exchange.com/questions/Q.20181972.html
http://www.experts-exchange.com/questions/Q.20256001.html
http://www.experts-exchange.com/questions/Q.20262969.html


To view your locked questions, please click the following link(s) and evaluate the proposed answer.
http://www.experts-exchange.com/questions/Q.20138318.html
http://www.experts-exchange.com/questions/Q.20139584.html

*****  E X P E R T S    P L E A S E  ******  Leave your closing recommendations if this item remains inactive another seven (7) days.  If you are interested in the cleanup effort, please click this link http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643 
POINTS FOR EXPERTS awaiting comments are listed here -> http://www.experts-exchange.com/commspt/Q.20277028.html
 
Moderators will finalize this question if in @7 days Asker has not responded.  This will be moved to the PAQ (Previously Asked Questions) at zero points, deleted or awarded.
 
Thank you everyone.
 
Moondancer
Moderator @ Experts Exchange
0
 
sudhakar_koundinyaCommented:


No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:


-- points to superschlonz


Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
sudhakar_koundinya
EE Cleanup Volunteer
---------------------
If you feel that your question was not properly addressed, or that none of the comments received were appropriate answers, please post your concern in THIS thread.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now