返回顶部

收藏

Java计算两个日期相差的天数

更多

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++;
            }
        }
    }
}

标签:java

收藏

0人收藏

支持

0

反对

0

发表评论