Solved

# Calculate difference of dates in days

Posted on 2004-11-08
226 Views
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
Question by:sasha_kv

LVL 13

Accepted Solution

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

LVL 13

Expert Comment

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

LVL 5

Assisted Solution

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

LVL 13

Expert Comment

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

### Suggested Solutions

1. Package the applet into a JAR file. The applet must be in a JAR file before a certificate can be attached to it. Use the jar JDK utility. If the applet was previously referenced with the help of a codebase attribute in  tag, replace the codebase …
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…