小编典典

持续时间2次

java

如何获取格式为2个字符串的持续时间YYYYMMDDTHHMMSS

我正在尝试使用Calendar类并检查getTimeInMillis()。我与此有关的问题是它不一致。知道我在做什么错吗?每次我运行该程序时,如果没有,输出40-70行到控制台。

public class DurationTester {

    /**
     * Get the duration between two given times
     * @param time1 yyyymmddThhmmss
     * @param time2 yyyymmddThhmmss
     * @return minutes between time1 and time2
     */
    public static int getDuration(String time1, String time2){
        int yyyy1 = Integer.parseInt(time1.substring(0,4));
        int mm1 = Integer.parseInt(time1.substring(4,6));
        int dd1 = Integer.parseInt(time1.substring(6,8));
        int hh1 = Integer.parseInt(time1.substring(9,11));
        int min1 = Integer.parseInt(time1.substring(11,13));

        int yyyy2 = Integer.parseInt(time2.substring(0,4));
        int mm2 = Integer.parseInt(time2.substring(4,6));
        int dd2 = Integer.parseInt(time2.substring(6,8));
        int hh2 = Integer.parseInt(time2.substring(9,11));
        int min2 = Integer.parseInt(time2.substring(11,13));

        Calendar cal1 = Calendar.getInstance();
        cal1.set(yyyy1, mm1, dd1, hh1, min1, 0);
        Calendar cal2 = Calendar.getInstance();
        cal2.set(yyyy2, mm2, dd2, hh2, min2, 0);
        long milliSec = cal1.getTimeInMillis()-cal2.getTimeInMillis();
        long nonNegativeMS = Math.abs(milliSec);
        long seconds = nonNegativeMS / 1000;
        long minutes = seconds / 60;        
        return (int)minutes;
    }

    public static void main(String[] args){
        String t1 = "20130108T150000";
        String t2 = "20130108T131500";

        int errors = 0;
        for(int i=0; i<5000; i++){
            int duration = getDuration(t1,t2);
            if(duration == 104){
                System.out.println("ERROR: Should only be 105 ("+errors++ +")");
            }
        }
    }
}

阅读 211

收藏
2020-09-28

共1个答案

小编典典

那是一个已记录的错误

尝试在设置日历之前清除日历:

cal1.clear();
cal1.set(yyyy1, mm1, dd1, hh1, min1, 0);

cal2.clear();
cal2.set(yyyy2, mm2, dd2, hh2, min2, 0);
2020-09-28