如何在Java中找出年月日中的两个日期之间的差异?
假设我有:具有 startDate 作为其属性变量的 Employee 模型和 Promotion 模型具有 promotionDate .我想找出员工在升职之前已经工作了多长时间,因此我必须找出promotionDate和startDate之间的区别.如果我将startDate命名为 employee.getStartDate(),将promotionDate命名为 promotion.getPromotionDate ,如何找到任何日期的年月日间差异,
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,
任何帮助将不胜感激.
更新:我解决了以下问题
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 ");
谢谢.
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);
时期
具有诸如 .getYears()
, .getMonths()
等的方法.
如果具有 java.util.Date
对象而不是int值 2015,1,1
,则可以将 Date
转换为 LocalDate
之前:
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();