有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用parseInt()和子字符串的java时差

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

我已经读取了字符串,使用substring函数提取字符串(直到“:”),然后转换为整数。提取效果非常好

我的问题在于计算。e、 g.-下午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) 个答案

  1. # 1 楼答案

    不要为此使用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
    
  2. # 2 楼答案

    要使代码可读和可测试,请创建助手方法

    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;
    }
    

    输出

    105
    1433