Solved

java.sql.date calculations

Posted on 2001-06-14
8
1,146 Views
Last Modified: 2008-02-01
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
Comment
Question by:pravin_tiwari
8 Comments
 
LVL 3

Expert Comment

by:superschlonz
Comment Utility
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
 
LVL 2

Expert Comment

by:venkat2000120699
Comment Utility
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
 
LVL 2

Expert Comment

by:venkat2000120699
Comment Utility
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
 
LVL 2

Expert Comment

by:venkat2000120699
Comment Utility
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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 3

Expert Comment

by:Sendoh
Comment Utility
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
 
LVL 3

Accepted Solution

by:
superschlonz earned 200 total points
Comment Utility
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
 
LVL 1

Expert Comment

by:Moondancer
Comment Utility
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility


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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now