what is wrong in this code ?
my intent is to calculate date duration in years including fractions.
example: If say two dates has duration = 1 year 6 months 30 days ....then I'd expect output as ( 1+ 6/12 +30/365) = 1.58 yrs (without round off)
Whats is the easy way to do it ?
my code :
package com;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Test {
public static void main(String[] arr) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String dateInString1 = "22-01-2015";
Date date1 = sdf.parse(dateInString1);
Calendar firstCal = Calendar.getInstance();
firstCal.setTime(date1);
String dateInString2 = "22-01-2016";
Date date2 = sdf.parse(dateInString2);
Calendar secondCal = Calendar.getInstance();
secondCal.setTime(date2);
// Convert date into millisecond
long firstMilliSecond = firstCal.getTimeInMillis();
long secondMilliSecond = secondCal.getTimeInMillis();
long differMilliSecond = firstMilliSecond - secondMilliSecond;
long years = differMilliSecond / (1000*60*60*24*365);
System.out.println("Total number of year between two date : "
+ years);
}
}
how to fix this ?