2 Replies Latest reply: Sep 4, 2007 4:20 AM by 807605 RSS

    does Calendar play with seconds?

    807605
      Hi,
      I am working on quick method that would take to dates and return the difference between those in working hours of business days..

      here is what ive came up with:
      private final int WORKDAY_START_TIME = 8;
      private final int WORKDAY_END_TIME = 16;
      
      private long calculateWorkTime(String startTime, String endTime) {
                
                
                long result = (8*60*60)+ 5*60*60 + 7*60 + 31;
                
                Date start = null;
                Date end = null;
                try {
                     SimpleDateFormat sdf = new SimpleDateFormat();
                     start = sdf.parse(startTime);
                     end = sdf.parse(endTime);
                } catch (ParseException e) {
                     e.printStackTrace();
                }
                
                String time = "01-09-2006  07:37:31";
                
                long seconds = 0;
                
                Calendar cal = Calendar.getInstance();
                cal.setTime(start);
                
                
                while(cal.getTime().getTime() < end.getTime())
                {                    
                     if (cal.get(Calendar.HOUR) < WORKDAY_START_TIME) {
                          int addition = WORKDAY_START_TIME - cal.get(Calendar.HOUR);
                          cal.add(Calendar.HOUR, addition);
                          cal.set(Calendar.MINUTE, 0);
                          cal.set(Calendar.SECOND, 0);
                     }
                     while(cal.get(Calendar.HOUR) < WORKDAY_END_TIME) {
                          cal.add(Calendar.SECOND,1);
                          seconds++;
                     }
                     cal.add(Calendar.DATE,1);
                     cal.set(Calendar.HOUR, WORKDAY_START_TIME);
                     cal.set(Calendar.SECOND, 0);
                     
                     int day = cal.get(Calendar.DAY_OF_WEEK);
                     if( day == Calendar.SATURDAY) {
                          cal.add(Calendar.SECOND,24*60*60); // SKIP SATURDAY
                     } else if (day == Calendar.SUNDAY ) {
                          cal.add(Calendar.SECOND,24*60*60); // SKIP SUNDAY
                          cal.add(Calendar.SECOND,8*60*60); // MONDAY 8 AM
                     }
                          continue;               
                }
                return seconds;
      the issue is the second while loop wich is supposed to add seconds as long as the Calendar date/time is still within a work day.

      the problem is that when debugging this while loop is infinite?? so my question is does the Calendar class know how to increase a date after enough seconds have passed?

      cheers