简化Java代码

时间:2013-07-03 14:08:47

标签: java date

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;

我确信有一种更容易/更简单的方式来编写这将需要更少的代码行?我只是看不到它。有没有其他人知道如何将其压缩成更干净的代码?

1 个答案:

答案 0 :(得分:3)

使用日历:

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

仅限日期解决方案

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

关于java的日期/日历系统:Why is the Java date API (java.util.Date, .Calendar) such a mess?