三个时间范围取交集工具类,几何算法

package com.na.train.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


public class TimeBanana {
public static Integer TimeB(Date s1, Date e1, Date s2, Date e2, Date s3, Date e3) {

Integer banana = 0;

// 开始时间取最小
Date min;
if (s1.before(s2) && s1.before(s3)) {
min = s1;
} else if (s2.before(s1) && s2.before(s3)) {
min = s2;
} else {
min = s3;
}

// 结束时间取最大
Date max;
if (e2.before(e1) && e3.before(e1)) {
max = e1;
} else if (e1.before(e2) && e3.before(e2)) {
max = e2;
} else {
max = e3;
}
// 交后面积
Integer Time = daysBetween(min, max);

// 总面积
Integer allTime = daysBetween(s1, e1) + daysBetween(s2, e2) + daysBetween(s3, e3);

if (Time <= allTime) {

Integer one = TwoTime(s1, e1, s2, e2);

Integer two = TwoTime(s1, e1, s3, e3);

Integer three = TwoTime(s3, e3, s2, e2);

Integer all = one + two + three;

if (one == 0 || two == 0 || three == 0) {

banana = 0;

} else {

banana = (all - (allTime - Time));
}

} else {

banana = 0;

}

return banana;

}

public static final Integer daysBetween(Date early, Date late) {

java.util.Calendar calst = java.util.Calendar.getInstance();

java.util.Calendar caled = java.util.Calendar.getInstance();

calst.setTime(early);

caled.setTime(late);

calst.set(java.util.Calendar.HOUR_OF_DAY, 0);

calst.set(java.util.Calendar.MINUTE, 0);

calst.set(java.util.Calendar.SECOND, 0);

caled.set(java.util.Calendar.HOUR_OF_DAY, 0);

caled.set(java.util.Calendar.MINUTE, 0);

caled.set(java.util.Calendar.SECOND, 0);

int days = ((int) (caled.getTime().getTime() / 1000) - (int) (calst.getTime().getTime() / 1000)) / 3600 / 24;

return days+1;

}


public static Integer TwoTime(Date startDate, Date endDate, Date start, Date end) {

Date maxend = null;

Date minstart = null;

if (end.before(endDate)) {

maxend = endDate;

} else {

maxend = end;

}

if (start.before(startDate)) {

minstart = start;

} else {

minstart = startDate;

}

Integer mm = (daysBetween(startDate, endDate) + daysBetween(start, end)) - daysBetween(minstart, maxend);

if (mm < 0) {

mm = 0;

}

return mm;

}

public static void main(String[] args) {

String s1 = "2018-06-01";
String e1 = "2018-06-30";
String s2 = "2018-08-10";
String e2 = "2018-08-10";
String s3 = "2018-09-15";
String e3 = "2018-09-15";

Integer banana = 0;

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

try {
banana = TimeB(sdf.parse(s1), sdf.parse(e1), sdf.parse(s2), sdf.parse(e2), sdf.parse(s3), sdf.parse(e3));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("香蕉:" + banana);

}

}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页