给定一个人的年份、月份和日期,需要获取出生日期-例如-19年1月2日16-2010年9月16日(已手动计算,可能不准确)
发布于 2019-10-17 19:30:32
LocalDateTime.now().minusYears(years).minusMonths(months).minusDays(days)
发布于 2019-10-17 19:41:11
基本上,您可以使用用于日期和时间java.time
的现代API,尤其是类LocalDate
。它具有添加或减去时间单位的方法,如日、月和年。
public static void main(String[] args) {
System.out.println("Imagine someone being 19 years, 1 months and 2 days old today...");
LocalDate birthday = getBirthdayFromAge(19, 1, 2);
System.out.println("Then this person was born on "
+ birthday.format(DateTimeFormatter.ISO_DATE));
}
public static LocalDate getBirthdayFromAge(int years, int months, int days) {
return LocalDate.now()
.minusDays(days)
.minusMonths(months)
.minusYears(years);
}
下面的输出
Imagine someone being 19 years, 1 months and 2 days old today...
Then this person was born on 2000-09-15
发布于 2019-10-17 19:49:58
我会选择java.time.LocalDate
和java.time.Period
类。调用minus
方法可能不是最优的,因为它将为每个方法调用创建新的对象(像LocalDate
,LocalDateTime
这样的类是不可变的):
Period period = Period.of(19, 1, 2); //period of 19 years, 1 month, 2 days
LocalDate birthday = LocalDate.now().minus(period); // compute the birthday
String formattedDate = birthday.format(DateTimeFormatter.ofPattern("dd-MMMM-YYYY", Locale.UK));
System.out.println(formattedDate);
输出为:
15-September-2000
https://stackoverflow.com/questions/58431536
复制相似问题