1

Sorry, i've tried to code for date Months and Days remaining, unfortunately i get the wrong result. Any helps would be appreciated. Thanks!

SimpleDateFormat formatter= new SimpleDateFormat("dd-MM-yyyy");
String sdate    = "08-02-2016";
String edate     = "02-02-2017";   

Date startdate = formatter.parse(sdate);
Date enddate   = formatter.parse(eddate );

Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startdate);

Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(enddate);

int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR); //effdate -   currdate
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) -startCalendar.get(Calendar.MONTH); 
int diffDay= endCalendar.get(Calendar.DAY_OF_MONTH) -startCalendar.get(Calendar.DAY_OF_MONTH); 

Expected result : 11 months, 25 days

P/s : JodaTime not applicable.

user3835327
  • 1,194
  • 1
  • 14
  • 44
  • 3
    Are you using Java 8? It's never a good idea to try and calculate the difference between dates by subtracting, it doesn't take into consideration the peculiarities of date/time, that's why JodaTime exists... – MadProgrammer Nov 20 '14 at 03:47
  • All you need is some extra logic to deal with the case where CURDATE's day is less than EFFDATE's day. What part of that is causing you difficulty? – Dawood ibn Kareem Nov 20 '14 at 03:48
  • 1
    Yes, as MadProgrammer says, this is easy in Java 8 - you use `Period.between( ... )` passing a couple of `LocalDate` objects. So do you have Java 8? – Dawood ibn Kareem Nov 20 '14 at 03:52
  • @MadProgrammer , agree with you. As using subtracting method is not a good practice. But my java version is < 8, i cannot apply JodaTime to my system. May i know any other methods to do this ? – user3835327 Nov 20 '14 at 03:52
  • possible duplicate of [Elapsed Months calculation not giving correct result for dates with current month and day but a different year](http://stackoverflow.com/questions/22216132/elapsed-months-calculation-not-giving-correct-result-for-dates-with-current-mont) and [this](http://stackoverflow.com/q/7807119/642706) and [this](http://stackoverflow.com/q/22773412/642706) and [this](http://stackoverflow.com/q/567659/642706) and [this](http://stackoverflow.com/q/635935/642706) and many more. – Basil Bourque Nov 20 '14 at 05:53
  • @BasilBourque , dont you see all of those solution are with JodaTime ? – user3835327 Nov 20 '14 at 06:08
  • @user3835327 (a) Not true. The very [first Answer](http://stackoverflow.com/a/22216321/642706) to the very first Question I linked does *not* involve Joda-Time. Others as well. (b) The fact that many of the answers to the first dozen or so Questions found by searching "java date elapsed months" involve Joda-Time should tell you something. I did not cherry-pick the Joda-Time answers, quite the opposite. The problem is that the java.util.Date/.Calendar classes do not handle this kind of date-time problem well. That is why Joda-Time or java.time are suggested so strongly and so often. – Basil Bourque Nov 20 '14 at 06:21

2 Answers2

1

I would strongly advice you to use a robust api for reliable result, but if you insist of doing it manually, try with the following, it seems giving the correct result(at least for your test case):

    SimpleDateFormat formatter= new SimpleDateFormat("dd-MM-yyyy");
    String CURRDATE    = "08-02-2016";
    String EFFDATE     = "02-02-2017";   

    Date startdate = formatter.parse(CURRDATE);
    Date enddate   = formatter.parse(EFFDATE);

    Calendar startCalendar = new GregorianCalendar();
    startCalendar.setTime(startdate);

    Calendar endCalendar = new GregorianCalendar();
    endCalendar.setTime(enddate);

    int monthCount = 0;
    int firstDayInFirstMonth = startCalendar.get(Calendar.DAY_OF_MONTH);
    startCalendar.set(Calendar.DAY_OF_MONTH, 1);
    endCalendar.add(Calendar.DAY_OF_YEAR, -firstDayInFirstMonth+1);

    while (!startCalendar.after(endCalendar)) {     
        startCalendar.add(Calendar.MONTH, 1);
        ++monthCount;
    }

    startCalendar.add(Calendar.MONTH, -1); --monthCount;
    int remainingDays = 0;
    while (!startCalendar.after(endCalendar)) {
        startCalendar.add(Calendar.DAY_OF_YEAR, 1);
        ++remainingDays;
    }

    startCalendar.add(Calendar.DAY_OF_YEAR, -1);
    --remainingDays;

    int lastMonthMaxDays = endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    if (remainingDays >= lastMonthMaxDays) {
        ++monthCount;
        remainingDays -= lastMonthMaxDays;
    }

    int diffMonth = monthCount; 
    int diffDay = remainingDays; 

    System.out.println("diffMonth==="+diffMonth +" Month(s) and " + diffDay + " Day(s)");
Mooolo
  • 428
  • 2
  • 7
0

i think directly u can not get like z day y hr x min

but you can get separate day min sec and all like below -

    long diff = EFFDAT.getTime() - CURRDATE.getTime();
    long diffSeconds = diff / 1000 % 60;
    long diffMinutes = diff / (60 * 1000) % 60;
    long diffHours = diff / (60 * 60 * 1000);
    int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));

UPDATED

hope it can help - I think u need Java 8

LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);

Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);

System.out.println("You are " + p.getYears() + " years, " + p.getMonths() + " months, and " + p.getDays() + " days old. (" + p2 + " days total)");

reference Oracle Page

Deepak Sharma
  • 4,124
  • 1
  • 14
  • 31
  • No! Not all days are 24 hours. This fails roughly 25% of the time - that is, whenever the date range ends during daylight savings time and starts during winter. You also haven't answered the question about getting months and days. – Dawood ibn Kareem Nov 20 '14 at 04:43