如何在Java中找出几个月和几天中两个日期之间的差异? [重复]

问题描述 投票:0回答:1

假设我有:员工模型,其startDate作为其属性变量,而Promotion模型具有promotionDate。我想知道员工在晋升前的工作时间,我必须找到promotionDate和startDate之间的区别。如果我将startDate作为employee.getStartDate()和promotionDate作为promotion.getPromotionDate,我怎样才能找到任何日期的月份和日期的差异,

任何帮助将非常感激。

更新:我解决了以下问题

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

谢谢。

java date date-difference java-date
1个回答
3
投票

使用java8中的LocalDate.of(int year, int month, int dayOfMonth),您可以创建两个日期并找到差异:

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

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

Period.getYears().getMonths()等方法。

如果你有java.util.Date对象而不是int值2015, 1, 1,你可以在之前将Date转换为LocalDate

LocalDate startLocalDate = startDate.toInstant()
        .atZone(ZoneId.systemDefault())
        .toLocalDate();
© www.soinside.com 2019 - 2024. All rights reserved.