由于公司业务变更,计算夜间服务费晚上23点–早上5点为夜间服务费时间,按分钟收费,考虑各种情况最后想出简单计算规则
这里写代码片
/**
* 分钟计算单位
*/
private static final int MINTUS_TIME_UNIT=60000;
/**
* 天计算单位
*/
private static final int DAY_TIME_UNIT=24*3600000;
/**
* 计算夜间服务时长
* @param startTime
* @param timeLenght
* @return
*/
public static int getNightServiceTimeLong(Date startTime,long timeLong){
return getNightServiceTimeLong(startTime,new Date(startTime.getTime()+timeLong));
}
/**
* 计算夜间服务时长(返回单位分钟)
* @param startTime开始时间
* @param endTime 结束时间
* @return
*/
public static int getNightServiceTimeLong(Date startTime, Date endTime){
long startLong=getDateTimetoLong(startTime);
long endLong=getDateTimetoLong(endTime);
DateTime startDate=new DateTime(startTime).withTime(5,0,0, 0);
DateTime start=new DateTime(startTime).withTime(23,0,0, 0);
DateTime end=new DateTime(endTime).withTime(5,0,0, 0);
DateTime endDate=new DateTime(endTime).withTime(23,0,0, 0);
long startMillis=start.getMillis();
long endMillis=end.getMillis();
int sumMinus=calDayDiffer(startMillis,endDate.getMillis())*360;
int startDiffer=calMintusDiffer(startMillis,startLong);
if(startDiffer>0){
sumMinus-=startDiffer;
}
int endDiffer=calMintusDiffer(endMillis,endLong);
if(endDiffer<0){
sumMinus+=endDiffer;
}
int endMany=calMintusDiffer(endDate.getMillis(),endLong);
if(endMany>0){
sumMinus+=endMany;
}
int startMany=calMintusDiffer(startLong,Math.min(startDate.getMillis(),endLong));
if(startMany>0&&startMany<300){
sumMinus+=startMany;
}
return sumMinus;
}
private static long getDateTimetoLong(Date date){
return new DateTime(date).withSecondOfMinute(0).withMillisOfSecond(0).getMillis();
}
private static int calDayDiffer(long start,long end){
return (int)((end-start)/DAY_TIME_UNIT);
}
/**
* 计算时差 返回单位分钟
* @param start
* @param end
* @return
*/
private static int calMintusDiffer(long start,long end){
return (int)((end-start)/MINTUS_TIME_UNIT);
}