日期:2014-05-20 浏览次数:20898 次
package com.study.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class T {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date defStart = sdf.parse("2012-12-29 08:00:00");
Date defEnd = sdf.parse("2012-12-29 20:59:59");
Date start1 = sdf.parse("2012-12-29 08:00:00");
Date end1 = sdf.parse("2012-12-29 10:30:00");
Date start2 = sdf.parse("2012-12-29 15:00:00");
Date end2 = sdf.parse("2012-12-29 17:00:00");
List<Date[]> defDates = new ArrayList<Date[]>();
List<Date[]> dates = new ArrayList<Date[]>();
defDates.add(new Date[]{defStart, defEnd});
dates.add(new Date[]{start1, end1});
dates.add(new Date[]{start2, end2});
getFreeTimes(defDates, dates);
for(Date[] date : defDates){
System.out.println(sdf.format(date[0]) + "--" + sdf.format(date[1]));
}
}
public static void getFreeTimes(List<Date[]> defDates, List<Date[]> dates){
for(Date[] date : dates){
dateFilter(defDates);
for(int i = 0; i < defDates.size(); i++){
Date[] defDate = defDates.get(i);
Date[][] d = getFreeTimes(defDate, date);
if(d != null){
defDates.remove(defDate);
i--;
if(d.length >= 1){
defDates.add(d[0]);
}
if(d.length == 2){
defDates.add(d[1]);
}
}
}
}
}
private static void dateFilter(List<Date[]> dates){
if(dates != null){
for(int i = 0; i < dates.size(); i++){
Date[] date = dates.get(i);
if(date[0].getTime() == date[1].getTime()){
dates.remove(i);
i--;
}
}
}
}
private static Date[][] getFreeTimes(Date[] defDate, Date[] date){
Date[][] dates = new Date[2][2];
if(defDate != null && defDate.length == 2 && date != null && date.length == 2){
long defStartTime = defDate[0].getTime();
long defEndTime = defDate[1].getTime();
long startTime = date[0].getTime();