将两个时间值与系统当前时间进行比较

时间:2015-01-02 10:52:19

标签: java android calendar

我正在创建一个简单的考勤应用程序,我想获得系统的当前时间,如果当前时间是在上午8点到下午3点之间,则将值设置为“早上”。下面是我的代码我在日历类的'之前'和'之后'方法中遇到错误。请建议我使用它的正确方法。

try {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a");
        String currentTime = sdf.format(c.getTime());

        // start time
         String lwrLimit = " 08:30:00 AM";  
        java.util.Date time_1 = new SimpleDateFormat("HH:mm:ss").parse(lwrLimit);
        Calendar calendar_1 = Calendar.getInstance();
        calendar_1.setTime(time_1);

        // end time
        String  uprLimit  = " 03:59:59 PM";  
        java.util.Date time_2 = new SimpleDateFormat("HH:mm:ss").parse(uprLimit);
        Calendar calendar_2 = Calendar.getInstance();
        calendar_2.setTime(time_2);

     if (currentTime.after(time_1) && currentTime.before(time_2)) 
          {
             ed_shift.setText( "Morning");
          }


    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
} 

2 个答案:

答案 0 :(得分:3)

像这样检查

   Calendar presentDate = Calendar.getInstance();

    Calendar startDate = Calendar.getInstance();
    startDate.set(Calendar.HOUR_OF_DAY, 8);
    startDate.set(Calendar.MINUTE, 30);
    startDate.set(Calendar.SECOND, 0);

    Calendar endDate = Calendar.getInstance();
    endDate.set(Calendar.HOUR_OF_DAY, 15);
    endDate.set(Calendar.MINUTE, 0);
    endDate.set(Calendar.SECOND, 0);

    if (presentDate.after(startDate) && presentDate.before(endDate)) {
        // set morning here
    } else {
        // set your data here
    }

答案 1 :(得分:0)

根据您的代码,在java.lang.String类中查找方法之前和之后,因为currentTime在开头被定义为String。