gpt4 book ai didi

java - 如何获取两个日期之间的月份和天数

转载 作者:太空宇宙 更新时间:2023-11-04 06:24:07 25 4
gpt4 key购买 nike

抱歉,我尝试对剩余日期进行编码,不幸的是我得到了错误的结果。任何帮助将不胜感激。谢谢!

SimpleDateFormat formatter= new SimpleDateFormat("dd-MM-yyyy");
String sdate = "08-02-2016";
String edate = "02-02-2017";

Date startdate = formatter.parse(sdate);
Date enddate = formatter.parse(eddate );

Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startdate);

Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(enddate);

int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR); //effdate - currdate
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) -startCalendar.get(Calendar.MONTH);
int diffDay= endCalendar.get(Calendar.DAY_OF_MONTH) -startCalendar.get(Calendar.DAY_OF_MONTH);

预期结果:11个月零25天

P/s:JodaTime 不适用。

最佳答案

我强烈建议您使用强大的 api 来获得可靠的结果,但如果您坚持手动执行此操作,请尝试以下操作,它似乎给出了正确的结果(至少对于您的测试用例而言):

    SimpleDateFormat formatter= new SimpleDateFormat("dd-MM-yyyy");
String CURRDATE = "08-02-2016";
String EFFDATE = "02-02-2017";

Date startdate = formatter.parse(CURRDATE);
Date enddate = formatter.parse(EFFDATE);

Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startdate);

Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(enddate);

int monthCount = 0;
int firstDayInFirstMonth = startCalendar.get(Calendar.DAY_OF_MONTH);
startCalendar.set(Calendar.DAY_OF_MONTH, 1);
endCalendar.add(Calendar.DAY_OF_YEAR, -firstDayInFirstMonth+1);

while (!startCalendar.after(endCalendar)) {
startCalendar.add(Calendar.MONTH, 1);
++monthCount;
}

startCalendar.add(Calendar.MONTH, -1); --monthCount;
int remainingDays = 0;
while (!startCalendar.after(endCalendar)) {
startCalendar.add(Calendar.DAY_OF_YEAR, 1);
++remainingDays;
}

startCalendar.add(Calendar.DAY_OF_YEAR, -1);
--remainingDays;

int lastMonthMaxDays = endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
if (remainingDays >= lastMonthMaxDays) {
++monthCount;
remainingDays -= lastMonthMaxDays;
}

int diffMonth = monthCount;
int diffDay = remainingDays;

System.out.println("diffMonth==="+diffMonth +" Month(s) and " + diffDay + " Day(s)");

关于java - 如何获取两个日期之间的月份和天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27031366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com