我有一个字符串数组,可以像这样存储每天的总线间隔
eg. ["6:30", "6:45", "7:00", "7:15", "7:30", "7.45"..................]
我希望程序能够找到当天阵列中最近的时间以及系统上的时间。
例如。在上面的字符串数组中说我的系统时间是7:35然后它应该显示7:30和7:45作为最接近的时间
答案 0 :(得分:0)
我希望这会帮助你。
public class TestClass {
public static void main(String[] args){
String arr[]={"06:30","07:00","07:30","14:20","14:50","18:20"};
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
System.out.println("Your system time is :"+ sdf.format(cal.getTime()) );
System.out.println("So nearest timings are...");
String sys[]=sdf.format(cal.getTime()).toString().split(":");
// System.out.println(sys[0]);
for(String st:arr){
if(st.startsWith(sys[0]))
System.out.println(st);
}
}
}
output would be :
Your system time is :14:47
So nearest timings are...
14:20 14:50
答案 1 :(得分:0)
试试这个
String[] arr =new String[]{"6:30", "6:45", "7:00", "7:15", "7:30", "7:45"};
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
String currentTime=sdf.format(cal.getTime());
//nus interval
Integer interval=15;
for (String string : arr) {
if(Math.abs(Integer.valueOf(string.replaceFirst(":", ""))-Integer.valueOf(currentTime))<interval){
System.out.println(string);
}
}