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: 227
  • Last Modified:

Calculate difference of dates in days

I need to translate two functions from excel into java:

1)
Date1 = 01/30/2002
Today()-Date1 <= 365 * 3

2)
Date2 = 04//07/1997
Today - Date2 <  365 * 6

Thank you !!!



0
sasha_kv
Asked:
sasha_kv
  • 3
2 Solutions
 
petmagdyCommented:
Calendar cal = new GregorianCalendar();
cal.set(2003,1,31);
Date date1 = cal.getTime();
cal.set(1997,7,4);
Date now = new Date();
long d1 = date1.getTime(); //returns in milliseconds
long d2 = now.getTime(); //returns in milliseconds

daysSeparated = (d1-d2) /(1000*60*60*24*365);
0
 
petmagdyCommented:
offcourse the result is:
daysSeparated = now - 31/1/2003

but a little correction to my first comment:
>> daysSeparated = (d1-d2) /(1000*60*60*24*365);
I mean:
daysSeparated = (d2-d1) /(1000*60*60*24*365);

0
 
JK2429Commented:
import java.util.*;

public class CalcAge {

public static void main(String args[])
     {
     Calendar today = new GregorianCalendar();
     Calendar PastDate = new GregorianCalendar();
     
     today.setTime(new Date());

        PastDate.setTime(new Date(96,1,15,12,20));
// You can set the PastDate however you want to


     long InDays = (today.getTime().getTime() - PastDate.getTime().getTime())/86400000;
     int InYears = today.get(Calendar.YEAR)-PastDate.get(Calendar.YEAR);

        if (today.get(Calendar.MONTH) < PastDate.get(Calendar.MONTH))
        AgeInYears--;
   
     System.out.println( "Today is "+today.getTime());
     System.out.println( "Past Date was "+PastDate.getTime());
     System.out.println( "in days is "+AgeInDays);
     System.out.println( "in Years is "+AgeInYears);

     }
}
0
 
petmagdyCommented:
JK2429,
take care that our page editior is not of encourging of providing complete code with Class and main method ;)
we just provide tips
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

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