## Forum Stats

• 3,826,348 Users
• 2,260,631 Discussions

Discussions

# what is wrong in this code ?

Member Posts: 466
edited Apr 27, 2017 4:01PM

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 ?

• Member Posts: 1,503
edited Apr 27, 2017 10:35AM

1) the result of  (1000*60*60*24*365)  is too big for int you have  to use long (1000l*60*60*24*365)

2) if you want result with fraction you have to use fraction types:

double differMilliSecond = secondMilliSecond  - firstMilliSecond ;

double years = differMilliSecond / (1000l*60*60*24*365l);

• edited Apr 27, 2017 4:01PM
`how to fix this ?`

How to fix WHAT?

You haven't shown any output or said that the output is wrong.

You also need to FULLY define the requirements. Part of that means describing how to deal with leap years.

Is 366 days ONE year? Or is it 1.0027 years? Depends on whether a leap year is involved.

Also, rather than reinvent the wheel you should just use Java's Duration class to help with the work.

https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html

This discussion has been closed.