以毫秒为单位的日期差异到 localdatetime
date difference in mills to localdatetime
我计算了两个日期之间的差异后,我需要再次打印日期。
这是我尝试过的:
fun getRemainingTime(endTime: ZonedDateTime): Long {
val currentTime = ZonedDateTime.now(ZoneId.systemDefault())
return dateUtils.durationDifference(currentTime, endTime).toMillis()
}
但是当我再次尝试将其转换为如下所示的 localdate 时,它以 1970
开头。所以我需要计算出的实际日期。
LocalDateTime.ofInstant(Instant.ofEpochMilli(remainingDurationInMillis), ZoneId.systemDefault())
java.time.LocalDateTime
不是为了表示两个日期之间的差异而创建的。应该使用 java.time.Period
和 java.time.Duration
(see Oracle docs)。
A Duration
measures an amount of time using time-based values
(seconds, nanoseconds). A Period
uses date-based values (years,
months, days).
它们都有一个方便的 .between()
方法,您可以这样使用:
Duration diff = Duration.between(ZonedDateTime.now(ZoneId.systemDefault()), endTime);
之所以没有组合 class 将持续时间表示为年、月、日和小时、分钟、秒,是因为一天可能是 24 小时或 25 小时,具体取决于夏令时。所以
A Duration
of one day is exactly 24 hours long. A Period
of one day, when added to a ZonedDateTime
, may vary according to the time zone. For example, if it occurs on the first or last day of daylight saving time.
我建议你使用 Duration
class 如果你想漂亮地打印它,你必须像这样手动完成(感谢 this answer):
System.out.println(diff.toString()
.substring(2)
.replaceAll("(\d[HMS])(?!$)", " ")
.toLowerCase());
这将打印类似 370h 24m 14.645s
的内容。如果你想要日、月和年,你将不得不从秒计算它们并打印。
如果您使用的是 Java 9+,有一些方法可以获取持续时间中的天数、小时数、分钟数和秒数:
System.out.println(String.format("%sd %sh %sm %ss",
diff.toDaysPart(),
diff.toHoursPart(),
diff.toMinutesPart(),
diff.toSecondsPart()));
我计算了两个日期之间的差异后,我需要再次打印日期。
这是我尝试过的:
fun getRemainingTime(endTime: ZonedDateTime): Long {
val currentTime = ZonedDateTime.now(ZoneId.systemDefault())
return dateUtils.durationDifference(currentTime, endTime).toMillis()
}
但是当我再次尝试将其转换为如下所示的 localdate 时,它以 1970
开头。所以我需要计算出的实际日期。
LocalDateTime.ofInstant(Instant.ofEpochMilli(remainingDurationInMillis), ZoneId.systemDefault())
java.time.LocalDateTime
不是为了表示两个日期之间的差异而创建的。应该使用 java.time.Period
和 java.time.Duration
(see Oracle docs)。
A
Duration
measures an amount of time using time-based values (seconds, nanoseconds). APeriod
uses date-based values (years, months, days).
它们都有一个方便的 .between()
方法,您可以这样使用:
Duration diff = Duration.between(ZonedDateTime.now(ZoneId.systemDefault()), endTime);
之所以没有组合 class 将持续时间表示为年、月、日和小时、分钟、秒,是因为一天可能是 24 小时或 25 小时,具体取决于夏令时。所以
A
Duration
of one day is exactly 24 hours long. APeriod
of one day, when added to aZonedDateTime
, may vary according to the time zone. For example, if it occurs on the first or last day of daylight saving time.
我建议你使用 Duration
class 如果你想漂亮地打印它,你必须像这样手动完成(感谢 this answer):
System.out.println(diff.toString()
.substring(2)
.replaceAll("(\d[HMS])(?!$)", " ")
.toLowerCase());
这将打印类似 370h 24m 14.645s
的内容。如果你想要日、月和年,你将不得不从秒计算它们并打印。
如果您使用的是 Java 9+,有一些方法可以获取持续时间中的天数、小时数、分钟数和秒数:
System.out.println(String.format("%sd %sh %sm %ss",
diff.toDaysPart(),
diff.toHoursPart(),
diff.toMinutesPart(),
diff.toSecondsPart()));