java - Checking dates if it is in a range
问题描述
My Java FX app handles hours worked. I have work start and end time in 2 date fields. I succeeded in calculating the differences between 2 datesTime; but now how could I check if the result is in a night or day range???? The day begin at 6 and ends at 22h. For example someone who worked between 3Am till 11Pm. Here is below how I did to have the total number of hours worked.
public void CalculNbreJourTravaille() {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyy HH:mm");
try {
Date ddtt = format.parse(ddt.getText());
Date dftt = format.parse(dft.getText());
long diff = dftt.getTime() - ddtt.getTime();
long diffhours = diff / (60*60*1000)%24;
long diffdays = diff/(24*60*60*1000);
long total = diffhours + (diffdays*24);
result.setText(total + " Hours");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
We have workers who can work beyond 10PM, and the pay would not be the same. If they work after 10pm, they will have a special pay. We pay at the end of the work. They could would work only 10 days or more.
解决方案
You should use the new DateTimeFormatter
class to give you a LocalDateTime
object, which you can pull the hour from.
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
LocalDateTime localDateTimeFrom = format.parse(dateFrom.getText(), LocalDateTime::from);
LocalDateTime localDateTimeTo = format.parse(dateTo.getText(), LocalDateTime::from);
int hoursFrom = localDateTimeFrom.getHour();
int hoursTo = localDateTimeTo.getHour();
boolean workedNight = hoursFrom < 6 || hoursTo > 22;
推荐阅读
- javascript - 使用日期范围选择器使某些日期/时间无效?
- wordpress - 带有 ACF 字段的 Wordpress ColorMag 搜索输入定位
- php - 第二个下拉菜单仅识别第一个选项
- c - 当 /proc/meminfo 中使用 Vmalloc 时会增加
- amazon-web-services - 将 Neo4j 放入私有子网时无法访问数据库
- r - 将图例标签与 ggplot 左对齐
- javascript - Firestore 时间戳保存为地图
- asp.net-core - ASP.NET Core 3.0 Blazor 中的 HTML id 标记和 JS 文件
- ios - 从 TableView 打开 ViewController 时有几秒钟的延迟
- python - ValueError:无法将字符串转换为浮点数:(115.985)