计算两个 JDateChooser 值之间的差异
Calculate Difference between two JDateChooser Value
这是我的代码,但它不起作用。
Start.getDate();
End.getDate();
int diffInDays = (int)( (Start.getDate() - End.getDate()) / (1000 * 60 * 60 * 24));
System.out.println(diffInDays);
那么我怎样才能制作一个程序,让用户可以查看 2 个 JDateChooser 之间的区别。
尝试获取以毫秒为单位的时间并进行比较:
Date startDate = Start.getDate();
Date endDate = End.getDate();
// In milliseconds
long difference = endDate.getTime() - startDate.getTime();
int diffInDays = (int)(difference / 1000 / 60 / 60 / 24);
在减去 Date
对象之前,它们不是数字。你想比较他们的时间,这是数字。
要检查 JDateChooser
是否为空,只需执行以下操作:
if (Start == null) {
// code
}
或
if (Start != null) {
// code
}
免责声明:
You should NEVER subtract two milliseconds from each other,there are just to many rules which aren't taking into account (leap years, leap seconds, century boundaries, daylight savings) to make it even remotely accurate. You should either use Java 8's Time API or JodaTi e (oh and days aren't always 24 hours long). -MadProgrammer.
这是一个快速而肮脏的解决方案,但存在很多弱边缘情况。小心点。
Date/Time 计算是一个复杂的主题,通常最好使用专用库来解决。
Java 8
Instant start = Start.getDate().toInstance();
Instant end = End.getDate().getInstance();
Duration duration = Duration.between(start, end);
乔达时间
如果你不能使用Java 8,那么你应该使用Joda-Time代替
DateTime start = new DateTime(Start.geDate().getTime());
DateTime end = new DateTime(End.geDate().getTime());
// You might need to use end, start instead, depending on which
// is later
Duration duration = new Duration(start, end);
Period period = duration.toPeriod();
您可以查看此 answer 以了解如何设置值的格式
这是我的代码,但它不起作用。
Start.getDate();
End.getDate();
int diffInDays = (int)( (Start.getDate() - End.getDate()) / (1000 * 60 * 60 * 24));
System.out.println(diffInDays);
那么我怎样才能制作一个程序,让用户可以查看 2 个 JDateChooser 之间的区别。
尝试获取以毫秒为单位的时间并进行比较:
Date startDate = Start.getDate();
Date endDate = End.getDate();
// In milliseconds
long difference = endDate.getTime() - startDate.getTime();
int diffInDays = (int)(difference / 1000 / 60 / 60 / 24);
在减去 Date
对象之前,它们不是数字。你想比较他们的时间,这是数字。
要检查 JDateChooser
是否为空,只需执行以下操作:
if (Start == null) {
// code
}
或
if (Start != null) {
// code
}
免责声明:
You should NEVER subtract two milliseconds from each other,there are just to many rules which aren't taking into account (leap years, leap seconds, century boundaries, daylight savings) to make it even remotely accurate. You should either use Java 8's Time API or JodaTi e (oh and days aren't always 24 hours long). -MadProgrammer.
这是一个快速而肮脏的解决方案,但存在很多弱边缘情况。小心点。
Date/Time 计算是一个复杂的主题,通常最好使用专用库来解决。
Java 8
Instant start = Start.getDate().toInstance();
Instant end = End.getDate().getInstance();
Duration duration = Duration.between(start, end);
乔达时间
如果你不能使用Java 8,那么你应该使用Joda-Time代替
DateTime start = new DateTime(Start.geDate().getTime());
DateTime end = new DateTime(End.geDate().getTime());
// You might need to use end, start instead, depending on which
// is later
Duration duration = new Duration(start, end);
Period period = duration.toPeriod();
您可以查看此 answer 以了解如何设置值的格式