java两个日期取小_java 获取两个日期具体相差多少天

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

}

}

应该可以了,测试了多种情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值