当前位置: 代码迷 >> J2SE >> java求两个时间段的重合天数,该怎么解决
  详细解决方案

java求两个时间段的重合天数,该怎么解决

热度:230   发布时间:2016-04-24 02:21:38.0
java求两个时间段的重合天数,急!
RT
例如:
第一段时间:2010-01-01到2011-01-01
第二段时间:2010-06-01到2011-06-01
求此两段时间的重合天数!!

------解决方案--------------------
没有试过、我想思路是这样的:
首先比较年是不是重合的,如果是那么比较月,在比较天数。
计算出每个月的天数加起来就可以了。这方法比较笨。
不知道对LZ有木有用.
------解决方案--------------------
Java code
public class Test {    public static void main(String[] args) throws ParseException {        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");        Date d1Start = df.parse("2010-01-01");        Date d1End = df.parse("2011-01-01");        Date d2Start = df.parse("2010-06-01");        Date d2End = df.parse("2011-06-01");                System.out.println(calcOverlapDays(d1Start, d1End, d2Start, d2End));    }    public static int calcOverlapDays(Date range1Start, Date range1End,            Date range2Start, Date range2End) {        long range1StartTime = range1Start.getTime();        long range1EndTime = range1End.getTime();        long range2StartTime = range2Start.getTime();        long range2EndTime = range2End.getTime();        assert range1StartTime > range1EndTime;        assert range2StartTime > range2EndTime;        long overlapTime = Math.min(range1EndTime, range2EndTime)                - Math.max(range1StartTime, range2StartTime);        return (overlapTime < 0) ? 0                : (int) (overlapTime / 24 / 60 / 60 / 1000 + 1);    }}
------解决方案--------------------
不知道能不能满足你的要求!
Java code
        //String time1_star = "2011-01-01";        String time1_end = "2011-05-01";                String time2_star = "2011-04-01";        //String time2_end="2011-06-01";        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");        try {            Date time1 =sdf.parse(time1_end);            Date time2 =sdf.parse(time2_star);            long diffDay= (time1.getTime()-time2.getTime())/(3600*1000*24);            if(diffDay > 0){                System.out.println("重合天数为:"+diffDay);            }else{                System.out.println("没有重合天数");            }            System.out.println(diffDay);        } catch (ParseException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }
  相关解决方案