java根据开始时间和结束时间,计算中间天数,并打印
import java.text.SimpleDateFormat;
import java.util.Date;
public class Calcdate {
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
static SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
public static void main(String[] args)throws Exception{
Date beginTime = sdf.parse("2015-04-23 12:32:44");
// Date endTime = sdf.parse("2015-04-23 14:56:44");
Date endTime = sdf.parse("2015-04-29 14:56:44");
long diff = (endTime.getTime() - beginTime.getTime()) / (86400 * 1000);
System.out.println("diff = " + diff);
Date sb = null;
Date se = null;
if(diff == 0){
sb = beginTime;
se = endTime;
String ss = String.format("%d> Sb=%s, Se=%s", 1, Coder.DateTimeToStr(sb), Coder.DateTimeToStr(se));
System.out.println(ss);
}else {
int i = 0;
while (i <= diff) {
if (i == 0) {
sb = beginTime;
se = sdf.parse(ymd.format(sb) + " 23:59:59");
} else if (i == diff) {
sb = sdf.parse(ymd.format(endTime) + " 00:00:00");
se = endTime;
} else {
se = new Date(beginTime.getTime() + i * 24 * 60 * 60 * 1000);
sb = sdf.parse(ymd.format(se) + " 00:00:00");
se = sdf.parse(ymd.format(se) + " 23:59:59");
}
String ss = String.format("%d> Sb=%s, Se=%s", i, Coder.DateTimeToStr(sb), Coder.DateTimeToStr(se));
System.out.println(ss);
i++;
}
}
}
}
diff = 6
0> Sb=2015-04-23 12:32:44, Se=2015-04-23 23:59:59
1> Sb=2015-04-24 00:00:00, Se=2015-04-24 23:59:59
2> Sb=2015-04-25 00:00:00, Se=2015-04-25 23:59:59
3> Sb=2015-04-26 00:00:00, Se=2015-04-26 23:59:59
4> Sb=2015-04-27 00:00:00, Se=2015-04-27 23:59:59
5> Sb=2015-04-28 00:00:00, Se=2015-04-28 23:59:59
6> Sb=2015-04-29 00:00:00, Se=2015-04-29 14:56:44