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


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");

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值