Solved

java.sql.date calculations

Posted on 2001-06-14
8
1,151 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
ID: 6193275
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
ID: 6193312
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
ID: 6193348
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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 2

Expert Comment

by:venkat2000120699
ID: 6193371
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
 
LVL 3

Expert Comment

by:Sendoh
ID: 6194114
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
ID: 6194748
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
ID: 6957050
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
ID: 8950695


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

ScreenConnect 6.0 Free Trial

Discover new time-saving features in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
mockito example issue 8 72
thymeleaf natural templating vs JSP 2 98
Where to store the queries for modification of table 4 62
map related example 6 48
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
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…

773 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