您的位置:首页 > 编程语言 > Java开发

JAVA计算两个日期之间的天数

2009-04-11 12:31 726 查看
 

public
class CalcDate {
/**
* @param args
* @author wuyaowen
* function calculate distance of two date given
* such as 2009.03.05 ~ 2005.09.07
*/
public int calcDate(String dateBegin, String dateEnd){
int distance = 0;           // 时间之间的天数
String db = dateBegin;  // 开始日期
String de = dateEnd;    // 结束日期
int strby = 0; // substring of begin date year 开始日期的年份
int strbm = 0; // 开始日期的月份
int strbd = 0; // 开始日期的日子
int strey = 0;
int strem = 0;
int stred = 0;
// 类型转换
strby = Integer.parseInt(db.substring(0, 4));
strbm = Integer.parseInt(db.substring(5, 7));
strbd = Integer.parseInt(db.substring(8, 10));
strey = Integer.parseInt(de.substring(0, 4));
strem = Integer.parseInt(de.substring(5, 7));
stred = Integer.parseInt(de.substring(8, 10));
if(stred < strbd){
stred = stred + 30;
strem = strem -1;
}
if(strem < strbm){
strem = strem + 12;
strey = strey -1;
}
distance = (strey - strby)*365 + (strem - strbm)*30 + stred - strbd;
return distance;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CalcDate cd =
new CalcDate();
int dates = cd.calcDate("2005-09-07", "2009-03-05");
System.
out.print(dates/365 + " years " + dates%365/30 + " months " + dates%365%30 + " dates");
/**
debugging
int test = 1287%365/30;
System.out.print("/n" + test);
//test subString()
String str = "C12natown";
String subStr = str.substring(1, 3);
System.out.println(Integer.parseInt(subStr)-1);
*/

}
// End of main()
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息