刚看到有个求空余时间的帖子,于是着手写了一下,话不多说直接贴代码。以后只求以后自己遇到的时候可以不用再写了
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();
long endTime = date[1].getTime();
long start = startTime - defStartTime;
long end = defEndTime - endTime;
if(start < 0 || end < 0){
return null;
}
Date[] date1 = new Date[2];
date1[0] = new Date(defStartTime);
date1[1] = new Date(startTime);
Date[] date2 = new Date[2];
date2[0] = new Date(endTime);
date2[1] = new Date(defEndTime);
dates[0] = date1;
dates[1] = date2;
// System.out.println(sdf.format(dates[0][0]) + "--" + sdf.format(dates[0][1]));
// System.out.println(sdf.format(dates[1][0]) + "--" + sdf.format(dates[1][1]));
return dates;
}
return null;
}
}