当前位置:首页 > 开发 > 编程语言 > 编程 > 正文

如何计算两个日期之间的天数

发表于: 2012-10-11   作者:darrenzhu   来源:转载   浏览:
摘要: package date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; publ
package date;

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

public class CalculateNumberOfDatesBetween2Dates {
    public static void main(String[] args) {

	String firstDateStr = "20120901";
	String lastDateStr = "20121001";
	SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");//very important, "yyyyMMDD" is wrong
	Date firstDate = null;
	Date lastDate = null;
	try {
	    firstDate = sf.parse(firstDateStr);
	    lastDate = sf.parse(lastDateStr);
	} catch (ParseException e) {
	    e.printStackTrace();
	}

	Calendar c1 = Calendar.getInstance();

	List<Date> cancelDates = new ArrayList<Date>();
	if (firstDate != null && lastDate != null && firstDate.before(lastDate)) {
	    Date tempDate = firstDate;
	    do {
		cancelDates.add(tempDate);
		c1.setTime(tempDate);
		c1.add(Calendar.DAY_OF_MONTH, 1);//important, Calendar.DAY_OF_YEAR is wrong
		tempDate = c1.getTime();
	    } while (tempDate.before(lastDate));
	    cancelDates.add(lastDate);
	}

	for (Date date : cancelDates) {
	    System.out.println(sf.format(date));
	}
	System.out.println("There are " + cancelDates.size() + " days between " + sf.format(firstDate) + " and " + sf.format(lastDate) + ", inclusive");

    }
}

如何计算两个日期之间的天数

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号