I wrote the code below that will give me the difference between two dates and the result will be in years, months and days.
for me it's good code but the problem is with months coz It's fixed to 30 days
So if I subtract (1 feb 2014) - (1 jan 2014) It should be one month But with my code it will be 1 month 1 day
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int y_d = 365;
int m_d = 30;
Scanner scn = new Scanner(System.in);
System.out.println("Enter your first date: ");
System.out.print("Day : ");
int day1 = scn.nextInt();
System.out.print("Month : ");
int month1 = scn.nextInt();
System.out.print("Year : ");
int year1 = scn.nextInt();
Calendar cal1 = Calendar.getInstance();
cal1.set(year1,month1-1,day1);
System.out.println();
System.out.println("Enter your second date: ");
System.out.print("Day : ");
int day2 = scn.nextInt();
System.out.print("Month : ");
int month2 = scn.nextInt();
System.out.print("Year : ");
int year2 = scn.nextInt();
Calendar cal2 = Calendar.getInstance();
cal2.set(year2,month2-1,day2);
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();
long day = milis2 - milis1;
long days = day / (24*60*60*1000);
System.out.println();
System.out.println("The difference : " + days + " days");
long y_r = (days % y_d);
long m_r = (y_r % m_d);
System.out.println("The result is approximatly");
System.out.println(days/y_d + " year(s)");
System.out.println(y_r/m_d + " month(s)");
System.out.println(m_r + " day(s)");
}
}
Could I resolve this problem without using joda time???