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 stubCalcDate 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()}