我正在尝试使用 jsoup 从我所在城市的交通网站捕获特定车站的火车到达时间列表。
使用 jsoup 的 getElementById
方法,我能够返回一大串到达时间,如下所示:
7:00 7:30 8:00 8:30 9:00 9:30 ...
我想将这些到达时间与预定 Activity 进行比较。因此,对于此示例,如果用户在 8:45 有约会,我只想返回到达时间 8:30
。
我该如何去做呢?
最佳答案
所以你有字符串7:00 7:30 8:00 8:30 9:00 9:30 ...
如果您必须使用字符串,我想出了以下代码,可以帮助您实现最终结果:
int apptHour = 8, apptMin = 45; // appointment is 8:45
String arrivalTime = ""; // temp var to store latest acceptable arrival time
String times = "7:00 7:30 8:00 8:30 9:00 9:30";
String[] time = times.split(" "); // split your string "7:00 7:30 8:00" etc.
for (String s : time) {
String[] parts = s.split(":"); // split each time into hours and mins
// if appointment is on the hour, remove 1 minute so that we calculate the correct arrival
if (apptMin == 0) { apptHour--; apptMin = 59; }
if (Integer.parseInt(parts[0]) == apptHour) {
if (Integer.parseInt(parts[1]) < apptMin) {
arrivalTime = parts[0] + ":" + parts[1];
}
}
}
System.out.println(arrivalTime);
因此,对于本示例,它将打印 8:30
作为预约 8:45
的建议到达时间。如果您预约8:00
,它会建议7:30
作为到达时间,依此类推。
关于java - 如何在 Android 中比较字符串时间和事件时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20589582/