Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

what is wrong in this code ?

user575089Apr 27 2017 — edited Apr 27 2017

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 ?

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 25 2017
Added on Apr 27 2017
2 comments
274 views