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++; } } } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/10688.html