写一个计算年月日的工具类
这是一个简单的计算年月日的工具类示例:
import java.time.LocalDate;
import java.time.Period;
public class DateCalculator {
public static int calculateAge(LocalDate birthDate) {
LocalDate currentDate = LocalDate.now();
Period period = Period.between(birthDate, currentDate);
return period.getYears();
}
public static int calculateDaysBetween(LocalDate startDate, LocalDate endDate) {
Period period = Period.between(startDate, endDate);
return period.getDays();
}
public static int calculateMonthsBetween(LocalDate startDate, LocalDate endDate) {
Period period = Period.between(startDate, endDate);
return period.getMonths();
}
public static int calculateYearsBetween(LocalDate startDate, LocalDate endDate) {
Period period = Period.between(startDate, endDate);
return period.getYears();
}
public static void main(String[] args) {
LocalDate birthDate = LocalDate.of(1990, 1, 1);
LocalDate currentDate = LocalDate.now();
int age = calculateAge(birthDate);
System.out.println("Age: " + age);
int daysBetween = calculateDaysBetween(birthDate, currentDate);
System.out.println("Days between: " + daysBetween);
int monthsBetween = calculateMonthsBetween(birthDate, currentDate);
System.out.println("Months between: " + monthsBetween);
int yearsBetween = calculateYearsBetween(birthDate, currentDate);
System.out.println("Years between: " + yearsBetween);
}
}
这个工具类使用了Java 8中的LocalDate和Period类来计算年龄以及两个日期之间的天数、月数和年数差距。其中calculateAge方法计算了给定出生日期到当前日期的年龄,calculateDaysBetween、calculateMonthsBetween和calculateYearsBetween方法分别计算了两个日期之间的天数、月数和年数差距。
在主方法中,我们提供了一个出生日期(1990年1月1日)和当前日期,并使用这些方法来计算年龄以及两个日期之间的差距。输出结果为:
Age: 32
Days between: 11651
Months between: 384
Years between: 31
``
原文地址: https://www.cveoy.top/t/topic/iZ3F 著作权归作者所有。请勿转载和采集!