问题描述
问题的标题包括所有细节.
The title of the question includes all the details.
如果我有 BigDecimal seconds = new BigDecimal("32365423.56");
是否有将其转换为的 API 方法:
n年,n个月,n天,n小时,n分钟,n秒.
If I have BigDecimal seconds = new BigDecimal("32365423.56");
Is there API methods that convert this to:
n years, n months, n days, n hours, n minutes, n seconds.
如果时间以秒为单位不明确,则以秒为单位假设这些值:(我不限于这些值)
If time is ambiguous in seconds, then assume in seconds these values: (I'm not confined to these values)
BigDecimal year = new BigDecimal("31556908.8");
BigDecimal month = new BigDecimal("2629739.52");
BigDecimal day = new BigDecimal("86400");
BigDecimal hour = new BigDecimal("3600");
BigDecimal minute = new BigDecimal("60");
推荐答案
您可以使用 java.time.Duration
以 ISO-8601 标准 并作为 .Java-9 引入了一些更方便的方法.
You can use java.time.Duration
which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenient methods were introduced.
演示:
import java.math.BigDecimal;
import java.time.Duration;
public class Main {
public static void main(String[] args) {
BigDecimal seconds = new BigDecimal("32365423.56");
Duration duration = Duration.ofNanos(seconds.multiply(BigDecimal.valueOf(1_000_000_000)).longValue());
System.out.println(duration);
// Custom format
// ####################################Java-8####################################
String formattedDuration = String.format("%d days %d hours %d minutes %d seconds", duration.toDays(),
duration.toHours() % 24, duration.toMinutes() % 60, duration.toSeconds() % 60);
System.out.println(formattedDuration);
// ##############################################################################
// ####################################Java-9####################################
formattedDuration = String.format("%d days %d hours %d minutes %d seconds", duration.toDaysPart(),
duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart());
System.out.println(formattedDuration);
// ##############################################################################
}
}
输出:
PT8990H23M43.56S
374 days 14 hours 23 minutes 43 seconds
374 days 14 hours 23 minutes 43 seconds
Learn about the modern date-time API from Trail: Date Time.
- 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport 将大部分 java.time 功能向后移植到 Java 6 &7.
- 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请查看 Java 8+ APIs 可通过 desugaring 和 如何在 Android 项目中使用 ThreeTenABP.
- For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
- If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
这篇关于是否有将 BigDecimal(seconds) 转换为年、月、日、小时、分钟、秒的 API 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!