mardi 7 mai 2019

Simple way to go check if a request date is within a certain time. Using for loops and if statements

I have a project where i am creating shifts. Users can request days off so when im creating a shift i want to check if that user has requested that day off. I have used for and if statements to do this but it seems very messy and it doesn't always work. Is there a simpler way to do this?

This is my code for creating a shift.

Shift createShift(@RequestBody ShiftParams params)
    {

            User u = userService.findByFirstName(params.text);
        Set<User> userSets = new HashSet<>();
        userSets.add(u);

        List<Request> req = u.getRequests();

        if(req != null && req.isEmpty()) //This creates the shift if 
                                                   the user has no requests
        {
            Shift shift = new Shift();
            shift.setStart(params.start);
            shift.setEnd(params.end);
            shift.setUsersShifts(userSets);
            shiftService.save(shift);   
        }
        else 
        {

        for(Iterator<Request> it= req.iterator(); it.hasNext();)
        {
              Request empReq = it.next();

                 if(empReq.getStatus() == Status.Accepted) 
                {
                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //for string
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); //for localdate

        //Request start date in LocalDate
        Date d = empReq.getDate();
        String rDateStart = sdf.format(d);
        LocalDate reqStartDate = LocalDate.parse(rDateStart, formatter).minusDays(1);
        System.out.println("Req start date is " + reqStartDate);

        //Request end date in LocalDate
        int numDays = empReq.getNumDays();
        LocalDate endDateReq = reqStartDate.plusDays(numDays).plusDays(1);
        System.out.println("Request finish date is" + endDateReq);

        //Shift start date in LocalDate
        String shiftDate = (params.start).format(formatter);
        LocalDate formatDateTime = LocalDate.parse(shiftDate, formatter);
    System.out.println("Shift date in date format " + formatDateTime); 


        if(formatDateTime.isAfter(reqStartDate) && 
          formatDateTime.isBefore(endDateReq)) //checks is the user has requested day off
{
    System.out.println("The employee has requested that day off");
} else { // if they havent requested that day off the shift is created

        Shift shift = new Shift();
        shift.setStart(params.start);
        shift.setEnd(params.end);
        shift.setUsersShifts(userSets);
        shiftService.save(shift);

    }

      }

  }
return null;

    }

Aucun commentaire:

Enregistrer un commentaire