public class DateTest {
public static String getDate() {
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
Date dd = new Date();
return ft.format(dd);
}public static String getQuot(String time1, String time2) {
long quot = 0, days = 0, years = 0;String result="";SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
GregorianCalendar cal= new GregorianCalendar();
try {Date date1 = ft.parse(time1);Date date2 = ft.parse(time2);
if(date2.getTime()> date1.getTime()){
quot = date2.getTime() - date1.getTime();days = quot / 1000 / 60 / 60 / 24 ;
result=calculateYearsAndDays(date1,date2,days);
}else{quot = date1.getTime() - date2.getTime();days = quot / 1000 / 60 / 60 / 24 ;
result=calculateYearsAndDays(date2,date1,days);
} } catch (ParseException e) {e.printStackTrace();return result;}return result;}
public static String calculateYearsAndDays(Date date1,Date date2,long days){
System.out.println(days);
int years=0; if(days>=366){
GregorianCalendar cal= new GregorianCalendar();//.getInstance();
for(int i=date1.getYear();i1)){
System.out.println("month="+date1.getMonth());
days=days-366;years++;}else{
System.out.println("month="+date1.getMonth());days=days-365;years++;
}}else if(cal.isLeapYear(i)){days=days-366;years++;
}else{days=days-365;years++;
}if(days<365){break;}}return years+" years and " + days + " days" ; }else{ return "0 years and " + days + " days" ; }}
public static void main(String[] args) {
String beginDate = "2002-03-12";
String endDate = "2023-03-20";
System.out.println(DateTest.getQuot(beginDate, endDate));
}
}
应该可以了,测试了多种情况。