时差使用parseInt()和substring

时间:2016-09-14 00:45:52

标签: java

我正在创建一个程序来查找两个输入之间的时差。开始和结束时间以12小时格式输入,例如上午9:30和上午11:15。

我已经读过字符串,使用substring函数提取字符串(直到':')然后转换为整数。萃取工作完全正常。

我遇到的问题是计算。例如 - 下午1:03至下午12:56之间的时差为1433分钟。但我的程序显示,相差713分钟。

我有代码的计算部分。任何建议将不胜感激。

// If-else statements to calculate the total time difference
 if((lower1.indexOf('a') == -1) && (lower2.indexOf('a') == -1) && (intMin1 <= 60) && (intMin2 <= 60)){
    timeDifference = Math.abs((((intHrs1+12)*60)+intMin1) - (((intHrs2+12)*60)+intMin2));
    System.out.println("The time difference is " + timeDifference + " minutes");
} else if((lower1.indexOf('a') != -1) && (lower2.indexOf('a') == -1) && (intMin1 <= 60) && (intMin2 <= 60)) {
    timeDifference = Math.abs((((intHrs2+12)*60)+intMin2) - ((intHrs1*60)+intMin1));         
    System.out.println("The time difference is " + timeDifference + " minutes");
} else if((lower1.indexOf('a') != -1) && (lower2.indexOf('a') != -1) && (intMin1 <= 60) && (intMin2 <= 60)){
    timeDifference = Math.abs(((intHrs2*60)+intMin1) - ((intHrs1*60)+intMin2));
    System.out.println("The time difference is " + timeDifference + " minutes");
} else if((lower1.indexOf('a') == -1) && (lower2.indexOf('a') != -1) && (intMin1 <= 60) && (intMin2 <= 60)){
    timeDifference = Math.abs((((24-(intHrs1+12))*60)+intMin1) - ((intHrs2*60)+intMin2));   
    System.out.println("The time difference is " + timeDifference + " minutes");
} else if(intMin1 >= 60){
     System.out.println("Error: The First time is invalid");
} else {
    System.out.println("Error: The second time is invalid");
}

2 个答案:

答案 0 :(得分:0)

DON&#39; T 为此使用parseInt和substring:

String input1 = "1:03pm".toUpperCase();
String input2 = "12:56pm".toUpperCase();

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mma");
LocalTime time1 = LocalTime.parse(input1, formatter);
LocalTime time2 = LocalTime.parse(input2, formatter);

long durationInMinutes = Duration.between(time1, time2).toMinutes()
if(durationInMinutes < 0) durationInMinutes += 1440; //1440 minutes per day

答案 1 :(得分:0)

To make your code readable and testable, create helper methods.

public static void main(String[] args) {
    System.out.println(minutesBetween("9:30am", "11:15am"));
    System.out.println(minutesBetween("1:03pm", "12:56pm"));
}
private static int minutesBetween(String time1, String time2) {
    int minutes = toMinuteOfDay(time2) - toMinuteOfDay(time1);
    if (minutes < 0)
        minutes += 1440;
    return minutes;
}
private static int toMinuteOfDay(String time) {
    int colon = time.indexOf(':');
    int hour = Integer.parseInt(time.substring(0, colon));
    int minute = Integer.parseInt(time.substring(colon + 1, colon + 3));
    if (hour == 12)
        hour = 0;
    if (time.indexOf('a') == -1)
        hour += 12;
    return hour * 60 + minute;
}

Output

105
1433