问题描述
我正在尝试从 timemachine 包中获取两个日期差异的输出。我可以从中获取年、月和日,但它不会以秒为单位返回。这是不是格式不对。找不到有关如何格式化日期的任何文档。
var a = LocalDate.dateTime(startDate); startDate is 2021-06-15 16:21:00.000
var b = LocalDate.dateTime(endDate); endDate is 2021-07-27 00:00:00.000
Period diff = b.periodSince(a);
diff = {Period} P1M12D
nanoseconds = 0
microseconds = 0
milliseconds = 0
seconds = 0
minutes = 0
hours = 0
days = 12
weeks = 0
months = 1
years = 0
解决方法
对于小时、分钟、秒等,您需要 java.time.Duration
,它以 ISO-8601 standards 为模型,并作为 {{3} 的一部分与 Java-8 一起引入}. Java-9 引入了一些方便的方法。
使用 Java 的演示:
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s.SSS",Locale.ENGLISH);
LocalDateTime start = LocalDateTime.parse("2020-06-15 16:21:00.000",dtf);
LocalDateTime end = LocalDateTime.parse("2021-10-27 00:00:00.000",dtf);
Period period = Period.between(start.toLocalDate(),end.toLocalDate());
System.out.println(period);
// Custom format
String elapsedPeriod = String.format("%d years %d months %d days",period.getYears(),period.getMonths(),period.getDays());
System.out.println(elapsedPeriod);
Duration duration = Duration.between(start,end);
System.out.println(duration);
// Custom format
// ####################################Java-8####################################
String formattedElapsedTime = String.format("%d hours %d minutes %d seconds",duration.toHours() % 24,duration.toMinutes() % 60,duration.toSeconds() % 60);
System.out.println(formattedElapsedTime);
// ##############################################################################
// ####################################Java-9####################################
formattedElapsedTime = String.format("%d hours %d minutes %d seconds",duration.toHoursPart(),duration.toMinutesPart(),duration.toSecondsPart());
System.out.println(formattedElapsedTime);
// ##############################################################################
System.out.println(elapsedPeriod + " " + formattedElapsedTime);
}
}
输出:
P1Y4M12D
1 years 4 months 12 days
PT11959H39M
7 hours 39 minutes 0 seconds
7 hours 39 minutes 0 seconds
1 years 4 months 12 days 7 hours 39 minutes 0 seconds
从 ONLINE DEMO 了解有关现代 Date-Time API 的更多信息。