检查给定的时间戳是否位于android

时间:2017-02-23 06:16:52

标签: java android datetime

我想检查给定的时间戳是否位于两个时间戳

之间

以下是我的代码:

public static boolean isTimeBetweenTwoTime(String initialTime, String finalTime, String currentTime) throws ParseException {
        String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
        if (initialTime.matches(reg) && finalTime.matches(reg) && currentTime.matches(reg)) {
            boolean valid = false;

            //Start Time
            java.util.Date inTime = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(initialTime);
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(inTime);

            //Current Time
            java.util.Date checkTime = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(currentTime);
            Calendar calendar3 = Calendar.getInstance();
            calendar3.setTime(checkTime);

            //End Time
            java.util.Date finTime = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(finalTime);
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(finTime);

            if (finalTime.compareTo(initialTime) < 0) {
                calendar2.add(Calendar.DATE, 1);
                calendar3.add(Calendar.DATE, 1);
            }

            java.util.Date actualTime = calendar3.getTime();
            if ((actualTime.after(calendar1.getTime()) || actualTime.compareTo(calendar1.getTime()) == 0)&& actualTime.before(calendar2.getTime())) {
                valid = true;
            }
            return valid;
        } else {
            throw new IllegalArgumentException("Not a valid time, expecting MM/dd/yyyy HH:mm:ss format");
        }

}

但它不适合我,请帮助

1 个答案:

答案 0 :(得分:2)

尝试这个简单的逻辑:

    long mills = System.currentTimeMillis();
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    Date resultdate = new Date(mills);
    String currentTime = sdf.format(resultdate);
    System.out.println(sdf.format(resultdate));

    try{
        java.util.Date inTime1 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(initialTime);
        java.util.Date inTime2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(finalTime);
        java.util.Date inTime3 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(currentTime);

        if (inTime3.getTime() > inTime1.getTime() && inTime3.getTime() < inTime2.getTime()){
            Log.e("TimeDifference","inTime3 is between inTime1 and inTime2");
            return true;
        }else{
            Log.e("TimeDifference","in Else Condition");
            return false;
        }

    }catch (Exception e){
        e.printStackTrace();
        return false;
    }

请告诉您是否有任何问题。