How to find difference between two dates in years months and days in Java? [duplicate]

亡梦爱人 提交于 2021-02-19 06:19:06

问题


Suppose I have : Employee model which has startDate as its property variable and Promotion model has promotionDate. I want to find out for how long employee has worked until his promotion for which I have to find difference between promotionDate and startDate. If I get startDate as employee.getStartDate() and promotionDate as promotion.getPromotionDate, how can I find difference in years months and days for any dates,

Any help would be really appreciated.

UPDATE : I SOLVED PROBLEM AS BELOW

String startDate = "2018-01-01";
String promotionDate = "2019-11-08";

LocalDate sdate = LocalDate.parse(startDate);
LocalDate pdate = LocalDate.parse(promotionDate);

LocalDate ssdate = LocalDate.of(sdate.getYear(), sdate.getMonth(), sdate.getDayOfMonth());
LocalDate ppdate = LocalDate.of(pdate.getYear(), pdate.getMonth(), pdate.getDayOfMonth());

Period period = Period.between(ssdate, ppdate);
System.out.println("Difference: " + period.getYears() + " years " 
                                  + period.getMonths() + " months "
                                  + period.getDays() + " days ");

Thank you.


回答1:


Using LocalDate.of(int year, int month, int dayOfMonth) from java8 you can create two dates and find the difference:

LocalDate firstDate = LocalDate.of(2015, 1, 1);
LocalDate secondDate = LocalDate.of(2018, 3, 4);

Period period = Period.between(firstDate, secondDate);

Period has such methods as .getYears(), .getMonths() etc.

If you have java.util.Date objects instead of int values 2015, 1, 1, you can convert Date to LocalDate before:

LocalDate startLocalDate = startDate.toInstant()
        .atZone(ZoneId.systemDefault())
        .toLocalDate();


来源:https://stackoverflow.com/questions/54967602/how-to-find-difference-between-two-dates-in-years-months-and-days-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!