-2
Date oDate= Entitlement_End_Date__c; //Date class from java.util

Double factor=0;

if(oDate.daysBetween(date.today())>0){
  //i.e if days between oDate and today is positive, means that oDate happened before //today's day thus meaning product is expried. 

  factor=((oDate.daysBetween(date.today())/365.00));
  if(factor>1) //greater than one year
    factor=1; // set the factor as one
  factor+=(date.today().daysBetween(TheEndDate)/365.00); //if factor is greater than //one, we want to find the exact amount of time it has expired for. 
}
else{
  factor=oDate.daysBetween(TheEndDate)/365.00;

I'm sure that there's an easier/simpler way of writing this that will require less lines of code? I just can't see it. Does anyone else know how to compress this into cleaner code?

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
user2405875
  • 133
  • 8
  • 2
    I'm not totally sure this question is even on topic (maybe code review?). But either way; some text as to what this code is supposed to do would be helpful – Richard Tingle Jul 03 '13 at 14:10
  • 11
    For improving currently working code, you might consider http://codereview.stackexchange.com – James Montagne Jul 03 '13 at 14:11
  • use modulus division when checking for factor if you dont expect it to be grater then 2 – Martin Larsson Jul 03 '13 at 14:12
  • 2
    *Always* use a pair of `{}` around `if` or `else` blocks. Use whitespace and indention. –  Jul 03 '13 at 14:14
  • Presumably daysBetween calculates the number of days between the one in this instance of Date and the supplied Date, and returns and integer. You call it twice for the same argument. Instead store the result in a local variable, and use the stored result for the second use. – NickJ Jul 03 '13 at 14:15
  • 1
    Regarding Tichodroma's comment, indeed, the multiline-braceless-if can lead to errors later on, see http://cafe.elharo.com/blogroll/braceless-if-considered-harmful/ – Richard Tingle Jul 03 '13 at 14:16
  • Date is actually the same class as java.util.Date. I'll comment the code a little to help clear up any misconceptions. – user2405875 Jul 03 '13 at 14:17

1 Answers1

3

Using a Calendar:

final Date endDate;
final Date startDate;


Long diff = endDate.getTime() - startDate.getTime(); // calculate the difference
Date dateDiff = new Date(diff);                      // convert it to a date
Calendar c = Calendar.getInstance();                 // get a calendar instance
c.setTime(dateDiff);                                 // set it to the calendar
int yearDiff = c.get(Calendar.YEAR)-1970;            // read the year and substract the "0-year" value which is 1970

Dates only solution

final long YEAR_IN_MILLIS = 1000L*60L*60L*24L*365L;
int yearDiff = (endDate.getTime()-startDate.getTime())/YEAR_IN_MILLIS;

And regarding java's date / calendar system: Why is the Java date API (java.util.Date, .Calendar) such a mess?

Community
  • 1
  • 1
Matyas
  • 13,473
  • 3
  • 60
  • 73