[英]Difference between two date and times
I need to find difference between to times.我需要找到时间之间的差异。 This is my code
这是我的代码
LocalDateTime ltdNow = LocalDateTime.now();
LocalDateTime ltdThen = LocalDateTime.parse("2020-07-30T08:00:00");
Duration duration = Duration.between(ltdNow, ltdThen);
System.out.println(duration.toDays + " Days and " + duration.toHours);
However i need it in this format 23 Days and 17 Hours
but it gives me large number like 19804
as the hour.但是我需要这种格式的
23 Days and 17 Hours
,但它给了我很大的数字,比如19804
作为小时。 How can i convert it to this format?我怎样才能把它转换成这种格式?
toHours()
does exactly what it says: The number of hours between the two dates. toHours()
就像它所说的那样:两个日期之间的小时数。
Try toHoursPart()
, I think that's what you're looking for:尝试
toHoursPart()
,我认为这就是您要寻找的:
System.out.println(duration.toDays() + " Days and " + duration.toHoursPart());
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
LocalDateTime ltdThen = LocalDateTime.parse("2020-07-30T08:00:00");
LocalDateTime ltdNow = LocalDateTime.now();
// ###########With Java-8###########
long days = ltdNow.until(ltdThen, ChronoUnit.DAYS);
long hours = ltdNow.until(ltdThen, ChronoUnit.HOURS);
System.out.println(days + " days and " + (hours % 24) + " hours.");
// ###########Java-9 onwards###########
Duration duration = Duration.between(ltdNow, ltdThen);
System.out.println(duration.toDaysPart() + " days and " + duration.toHoursPart() + " hours.");
}
}
Output: Output:
22 days and 15 hours.
22 days and 15 hours.
Note: Duration#toDaysPart
and Duration#toHoursPart
was introduced with Java-9.注意:
Duration#toDaysPart
和Duration#toHoursPart
是在 Java-9 中引入的。
ZoneId zone = ZoneId.of("Europe/Stockholm");
ZonedDateTime zdtNow = ZonedDateTime.now(zone);
ZonedDateTime zdtThen = LocalDateTime.parse("2020-10-26T08:00:00").atZone(zone);
long days = ChronoUnit.DAYS.between(zdtNow, zdtThen);
ZonedDateTime afterDays = zdtNow.plusDays(days);
long hours = ChronoUnit.HOURS.between(afterDays, zdtThen);
System.out.println("" + days + " days and " + hours + " hours");
Output when running today just before 18:00 Swedish time: Output 在瑞典时间今天 18:00 之前运行时:
110 days and 14 hours
110天14小时
Messages:留言:
Duration
class to calculate days.Duration
class 来计算天数。 It calculates a day as always 24 hours.Duration
.Duration
。Use Period:使用期限:
LocalDateTime ltdNow = LocalDateTime.now();
LocalDateTime ltdThen = LocalDateTime.parse("2020-07-30T08:00:00");
Period p = Period.between(ltdThen , ltdNow );
long p2 = ChronoUnit.DAYS.between(ltdThen , ltdNow );
System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +
" months, and " + p.getDays() +
" days old. (" + p2 + " days total)");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.