gpt4 book ai didi

Java Period 转换日期为 float

转载 作者:行者123 更新时间:2023-12-04 01:10:24 25 4
gpt4 key购买 nike

我有生日和第二个 LocalDate.now()我使用 Periof 打印这个

            Period test = Period.between(dateofbirth,LocalDate.now());

但是如果我想打印这个错误“P5Y8M11D”

我该怎么做才能得到它-“你在世界上生活了 10,23 年”

最佳答案

Period#getYears

P5Y8M11DPeriod#toString 的默认格式.您可以获得期间的组成部分,例如根据您的要求使用其相应的访问器方法从 Period 的对象获取年、月、日等。

演示:

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.Locale;

public class Main {
public static void main(String[] args) {
LocalDate dateofbirth = LocalDate.of(1975, 7, 15);
Period test = Period.between(dateofbirth, LocalDate.now());
System.out.printf("You have lived in the world for %d years.%n", test.getYears());

double years = test.getYears() + test.getMonths() / 12.0 + test.getDays() / 365.0;
System.out.printf("You have lived in the world for %.2f years.%n", years);

DecimalFormat format = (DecimalFormat) NumberFormat.getNumberInstance(Locale.GERMAN);
format.applyPattern("#,##0.00");
String formattedValue = format.format(years);
System.out.printf("You have lived in the world for %s years.%n", formattedValue);
}
}

输出:

You have lived in the world for 45 years.
You have lived in the world for 45.36 years.
You have lived in the world for 45,36 years.

关于Java Period 转换日期为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65023133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com