Example usage for org.joda.time Days daysBetween

List of usage examples for org.joda.time Days daysBetween

Introduction

In this page you can find the example usage for org.joda.time Days daysBetween.

Prototype

public static Days daysBetween(ReadablePartial start, ReadablePartial end) 

Source Link

Document

Creates a Days representing the number of whole days between the two specified partial datetimes.

Usage

From source file:energy.usef.pbcfeeder.PbcFeeder.java

License:Apache License

/**
 * @param date//from w  w  w  .j  a v  a  2  s  . c  om
 * @param startPtuIndex of the list starting from 1 till 96 (PTU_PER_DAY).
 * @param amount
 * @return
 */
public List<PbcStubDataDto> getStubRowInputList(LocalDate date, int startPtuIndex, int amount) {
    if (startPtuIndex > PTU_PER_DAY) {
        date = date.plusDays((int) Math.floor(startPtuIndex / PTU_PER_DAY));
        startPtuIndex = startPtuIndex % PTU_PER_DAY;
    }

    // Match PTU-index with requested startIndex and date from ExcelSheet.
    LocalDate epochDate = new LocalDate("1970-01-01");
    int daysDif = Days.daysBetween(epochDate, date).getDays();
    int ptuOffset = (daysDif % DAYS_IN_SPREADSHEET) * PTU_PER_DAY + startPtuIndex - 1;
    List<PbcStubDataDto> pbcStubDataDtoList = new ArrayList<>();

    // Loop over stubRowInputList, if necessary, to get requested amount of ptus.
    do {
        int toIndex = 0;
        if (ptuOffset + amount > stubRowInputList.size()) {
            toIndex = stubRowInputList.size();
        } else {
            toIndex = ptuOffset + amount;
        }
        amount -= (toIndex - ptuOffset);

        pbcStubDataDtoList.addAll(stubRowInputList.subList(ptuOffset, toIndex));
        ptuOffset = 0;
    } while (amount > 0);

    // Create and set PtuContainer for pbcStubDataDto.

    int lastPtuIndex = 0;
    for (PbcStubDataDto pbcStubDataDto : pbcStubDataDtoList) {
        int ptuIndex = pbcStubDataDto.getIndex() % PTU_PER_DAY;
        if (ptuIndex == 0) {
            ptuIndex = PTU_PER_DAY;
        }
        if (ptuIndex < lastPtuIndex) {
            date = date.plusDays(1);
        }
        PbcPtuContainerDto ptuContainerDto = new PbcPtuContainerDto(date.toDateMidnight().toDate(), ptuIndex);
        pbcStubDataDto.setPtuContainer(ptuContainerDto);
        lastPtuIndex = ptuIndex;
    }
    return pbcStubDataDtoList;
}

From source file:entity.Project.java

public Integer getDurationInDays() {
    if (this.closedAt == null) {
        return null;
    }//from ww  w .  j av a2  s .  c  o  m
    return Days.daysBetween(new DateTime(this.createdAt), new DateTime(this.closedAt)).getDays();
}

From source file:eu.uqasar.model.tree.Project.java

License:Apache License

@JsonIgnore
public int getDurationInDays() {
    DateTime end = new DateTime(getEndDate());
    DateTime start = new DateTime(getStartDate());
    return Days.daysBetween(start, end).getDays();
}

From source file:eu.uqasar.model.tree.Project.java

License:Apache License

@JsonIgnore
public int getElapsedDays() {
    DateTime start = new DateTime(getStartDate());
    int elapsed = Days.daysBetween(start, DateTime.now()).getDays();
    int daysTotal = getDurationInDays();
    return Math.min(elapsed, daysTotal);
}

From source file:eu.uqasar.model.tree.Project.java

License:Apache License

@JsonIgnore
public int getRemainingDays() {
    DateTime end = new DateTime(getEndDate());
    int remainingDays = Days.daysBetween(DateTime.now(), end).getDays();
    return Math.max(0, remainingDays);
}

From source file:fr.inria.atlanmod.decision.ui.DecisionEngine.java

License:Open Source License

private boolean deadlineMet(Rule rule, ProxyTask task) {
    Deadline deadline = rule.getDeadline();
    if (deadline instanceof Timer) {
        Timer timer = (Timer) deadline;
        Date creationDate = task.getCreationDate();
        Days days = Days.daysBetween(LocalDate.fromDateFields(creationDate),
                LocalDate.fromDateFields(new Date()));

        int deadlineDays = timer.getTimeStamp();
        if (days.getDays() < deadlineDays)
            return false;
        else// w w  w .j  ava 2s. c  o  m
            return true;
    } else if (deadline instanceof WaitForVote) {
        WaitForVote waitForVote = (WaitForVote) deadline;
        List<Role> rolesToWaitFor = waitForVote.getRoles();

        List<User> allUsers = collaborations.getUsers();
        List<User> usersToVote = new ArrayList<User>();
        for (User user : allUsers) {
            for (Role role : user.getRoles()) {
                boolean found = false;
                for (Role roletToWaitFor : rolesToWaitFor) {
                    if (role.getName().equals(roletToWaitFor.getName())) {
                        usersToVote.add(user);
                        found = true;
                        break;
                    }
                }
                if (found)
                    break;
            }
        }

        List<User> usersVoted = new ArrayList<User>();
        for (Vote vote : task.getCollaboration().getVotes()) {
            usersVoted.add(vote.getVotedBy());
        }

        // I'm not very proud of this, but I was having a hard afternoon 
        // and I didn't come up with other solution :(
        int totalUsersToVote = usersToVote.size();
        for (User userVoted : usersVoted) {
            for (User userToVote : usersToVote) {
                if (userVoted.getName().equals(userToVote.getName())) {
                    totalUsersToVote--;
                }
            }
        }

        if (totalUsersToVote == 0)
            return true;
        else
            return false;
    } else if (deadline instanceof OCLCondition) {
        OCLCondition oclCondition = (OCLCondition) deadline;
        // TODO consider OCL expressions
    }

    return true;
}

From source file:fr.nicopico.dashclock.birthday.BirthdayService.java

License:Apache License

@Override
protected void onUpdateData(int reason) {
    if (reason == UPDATE_REASON_SETTINGS_CHANGED) {
        updatePreferences();/*www. j  a  va2s  .c  om*/
    }

    final Resources res = getResources();
    final List<Birthday> birthdays = birthdayRetriever.getContactWithBirthdays(getApplicationContext(),
            contactGroupId);

    Configuration config = new Configuration();
    config.setToDefaults();

    // Disable/enable Android localization
    if (needToRefreshLocalization
            || (disableLocalization && !DEFAULT_LANG.equals(Locale.getDefault().getLanguage()))) {
        if (disableLocalization) {
            config.locale = new Locale(DEFAULT_LANG);
        } else {
            // Restore Android localization
            //noinspection ConstantConditions
            config.locale = Resources.getSystem().getConfiguration().locale;
        }

        Locale.setDefault(config.locale);
        getBaseContext().getResources().updateConfiguration(config,
                getBaseContext().getResources().getDisplayMetrics());
    }

    DateTime today = new DateTime();

    int upcomingBirthdays = 0;
    String collapsedTitle = null;
    String expandedTitle = null;
    StringBuilder body = new StringBuilder();

    for (Birthday birthday : birthdays) {
        DateTime birthdayEvent;
        MonthDay birthdayDate = birthday.birthdayDate;
        try {
            birthdayEvent = birthdayDate.toDateTime(today);
        } catch (IllegalFieldValueException e) {
            if (birthdayDate.getDayOfMonth() == 29 && birthdayDate.getMonthOfYear() == 2) {
                // Birthday on February 29th (leap year) -> March 1st
                birthdayEvent = birthdayDate.dayOfMonth().addToCopy(1).toDateTime(today);
            } else {
                Log.e(TAG, "Invalid date", e);
                continue;
            }
        }

        // How many days before the birthday ?
        int days;
        if (birthdayEvent.isAfter(today) || birthdayEvent.isEqual(today)) {
            days = Days.daysBetween(today, birthdayEvent).getDays();
        } else {
            // Next birthday event is next year
            days = Days.daysBetween(today, birthdayEvent.plusYears(1)).getDays();
        }

        // Should the birthday be displayed ?
        if (days <= daysLimit) {
            upcomingBirthdays++;

            if (upcomingBirthdays == 1) {
                // A single birthday will be displayed
                collapsedTitle = birthday.displayName;
                expandedTitle = res.getString(R.string.single_birthday_title_format, birthday.displayName);
            }

            // More than 1 upcoming birthday: display contact name
            if (upcomingBirthdays > 1) {
                body.append("\n").append(birthday.displayName).append(", ");
            }

            // Age
            if (!birthday.unknownYear) {
                int age = today.get(DateTimeFieldType.year()) - birthday.year;
                body.append(res.getQuantityString(R.plurals.age_format, age, age));
                body.append(' ');
            }

            // When
            int daysFormatResId;
            switch (days) {
            case 0:
                daysFormatResId = R.string.when_today_format;
                break;
            case 1:
                daysFormatResId = R.string.when_tomorrow_format;
                break;
            default:
                daysFormatResId = R.string.when_days_format;
            }

            body.append(res.getString(daysFormatResId, days));
        } else {
            // All visible birthdays have been processed
            break;
        }
    }

    if (upcomingBirthdays > 0) {
        Intent clickIntent = buildClickIntent(birthdays.subList(0, upcomingBirthdays));

        if (upcomingBirthdays > 1) {
            collapsedTitle += " + " + (upcomingBirthdays - 1);
        }

        // Display message
        publishUpdate(
                new ExtensionData().visible(true).icon(R.drawable.ic_extension_white).status(collapsedTitle)
                        .expandedTitle(expandedTitle).expandedBody(body.toString()).clickIntent(clickIntent));
    } else {
        // Nothing to show
        publishUpdate(new ExtensionData().visible(false));
    }
}

From source file:gobblin.ingestion.google.webmaster.ProducerJob.java

License:Apache License

public List<? extends ProducerJob> partitionJobs() {
    DateTime start = dateFormatter.parseDateTime(getStartDate());
    DateTime end = dateFormatter.parseDateTime(getEndDate());
    int days = Days.daysBetween(start, end).getDays();
    if (days <= 0) {
        return new ArrayList<>();
    }/*  ww w  . j a  v  a2 s. com*/
    int step = days / 2;
    return Arrays.asList(
            new SimpleProducerJob(getPage(), getStartDate(), dateFormatter.print(start.plusDays(step))),
            new SimpleProducerJob(getPage(), dateFormatter.print(start.plusDays(step + 1)), getEndDate()));
}

From source file:hotelmgmt.HotelSystem.java

/**
 * Books or reserves a room for a customer.  Set flag true to reserve, false to book.
 * Checks with Room Manager for room type availability, if true returns price 
 * and sets customer balance.//  w  w w . ja  v  a  2 s. c o m
 * @param reserve is flag to indicate room reserve or booking
 * @param id is customer id number (must be valid and unique)
 * @param roomType is type of room the customer is interested in
 * @param in is date check in
 * @param out is date check out
 * @return boolean true if room booking is successful, false otherwise
 */
public boolean bookRoom(boolean reserve, int id, String roomType, LocalDate in, LocalDate out) {
    if (checkCustomerId(id)) { // check if customer id exists, proceed to booking room
        ArrayList<Purchase> purchaseList = cAccounts.get(id); // get pointer to array list object for this customer            
        if (reserve) { // customer makes reservation
            for (int i = 0; i < purchaseList.size(); i++) { // check for reservations in purchase list
                Purchase p = purchaseList.get(i);
                if (p.getReserve()) { // look at reservations in purchase list
                    if (p.getRoomType().equals(roomType) && p.getDateIn().isEqual(in)
                            && p.getDateOut().isEqual(out)) {
                        UserView.speakInfo("Reservation already exists.");
                        return false;
                    } // end if statement; compare reservation: room type, local date in | out                    
                } // end if statement; check purchase reserve flag                
            } // end for loop; purchase list scan
            if (roomMan.isRoomAvailable(roomType, in, out)) { // ask Room Manager if room type and dates are available
                Purchase pur = new Purchase(); // room available; proceed to make reservation
                pur.setRoomType(roomType);
                int numberOfDays = Days.daysBetween(in, out).getDays();
                pur.setBalance(roomMan.getRoomPrice(roomType) * numberOfDays);
                pur.setDateIn(in);
                pur.setDateOut(out);
                pur.setReserve(true);
                purchaseList.add(pur); // add reservation to purchase list
                roomMan.makeReserve(roomType, in, out); // notify Room Manager of reservation
                UserView.speakInfo("Reservation made.");
                //displayCustomerBalance(id); I took this out because it will add to list display
                return true;
            } else { // room not available
                UserView.speakInfo("Room type or dates not available.");
                return false;
            }
        } // end if statement for bookRoom reserve flag true

        else { // customer is not making a reservation
            for (int i = 0; i < purchaseList.size(); i++) { // check for prior reservations in purchase list
                Purchase p = purchaseList.get(i);
                if (p.getReserve()) { // look at reservations in purchase list & compare to input args
                    if (p.getRoomType().equals(roomType) && p.getDateIn().isEqual(in)
                            && p.getDateOut().isEqual(out)) {
                        p.setReserve(false); // change reserve status of purchase
                        for (int j = 0; j < cusList.size(); j++) { // find customer object for Room Manager
                            Customer c = cusList.get(j);
                            if (id == c.getId()) {
                                int r = roomMan.checkIn(roomType, c);
                                p.setRoom(r);
                                UserView.speakInfo("Removed prior reservation, checked it.");
                                //displayCustomerBalance(id); took out because it will display to list
                                return true;
                            } // end if statement; compare given id to customer id
                        } // end for loop; customer object search                                                        
                    } // end if statement; compare reservation: room type, local date in | out                    
                } // end if statement; check purchase reserve flag                
            } // end for loop; purchase list scan

            // previous for loop falls through; no reservations match input args, proceed with normal check-in
            for (int k = 0; k < cusList.size(); k++) { // find customer for Room Manager
                Customer c = cusList.get(k);
                if (id == c.getId()) {
                    roomMan.makeReserve(roomType, in, out);
                    int r = roomMan.checkIn(roomType, c);
                    Purchase pur = new Purchase(); // make new Purchase; mark as check-in
                    pur.setRoomType(roomType);
                    int numberOfDays = Days.daysBetween(in, out).getDays();
                    pur.setBalance(roomMan.getRoomPrice(roomType) * numberOfDays);
                    pur.setDateIn(in);
                    pur.setDateOut(out);
                    pur.setRoom(r);
                    purchaseList.add(pur); // add to purchase list
                    UserView.speakInfo("Check-in made.");
                    //displayCustomerBalance(id); displays to list object
                    return true;
                } // end if statement; compare customer id to given id
            } // end for loop; customer list search                                                                
        } // end else statement; customer not making reservation
        UserView.speakError("Error occurred during check-in.  Please try again.");
        return false;
    } // end if statement; checkCustomerId
    else {
        UserView.speakError("Error with customer id.  Check id or try again.");
        return false;
    } // end else statement; checkCustomerId   
}

From source file:hotelmgmt.UserView.java

/**
 * The Customer Menu/*from   w  w  w  .  j a v a 2 s  .  co m*/
 * @param ID the customer's id
 */
public void customerMenu(int ID) {
    JFrame frame = new JFrame();
    frame.setTitle("Customer Menu");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    JPanel cusPanel = new JPanel();
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setPreferredSize(new Dimension(600, 550));
    //cusPanel.add(list);
    cusPanel.add(new JScrollPane(list));
    frame.add(cusPanel, BorderLayout.CENTER);

    //This is all creating the bottom row of buttons 
    JButton leftButton = new JButton("Left");
    leftButton.setVisible(false);
    leftButton.setPreferredSize(new Dimension(150, 26));
    JButton rightButton = new JButton("Right");
    rightButton.setVisible(false);
    rightButton.setPreferredSize(new Dimension(150, 25));
    JButton logoutButton = new JButton("Logout");
    logoutButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            logout();
            listModel.clear();
            frame.dispose();
        }
    });
    JPanel bottomPanel = new JPanel();
    bottomPanel.add(leftButton);
    bottomPanel.add(logoutButton);
    frame.add(bottomPanel, BorderLayout.SOUTH);

    //This is creating the top row of the frame and setting there
    TextField start, end;
    start = new TextField("", 20);
    end = new TextField("", 20);
    JButton roomsButton = new JButton("Display Rooms");
    roomsButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            listModel.clear();
            String startd = checkDate(start.getText());
            String endd = checkDate(end.getText());
            if (startd != "" && endd != "") {
                LocalDate startdate = LocalDate.parse(startd, DateTimeFormat.forPattern("MM/dd/yyyy"));
                LocalDate enddate = LocalDate.parse(endd, DateTimeFormat.forPattern("MM/dd/yyyy"));
                int numdays = Days.daysBetween(startdate, enddate).getDays();
                if (numdays <= 0)
                    speakError("Check out date must be after check in date");
                else
                    hotel.displayRoomsAvailable(startdate, enddate);
                leftButton.setText("Reserve Room");
                leftButton.setVisible(true);
                for (ActionListener al : leftButton.getActionListeners())
                    leftButton.removeActionListener(al);
                leftButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        try {
                            //Note here how to parse a string
                            //This line will find a string and return the position of first character
                            int priceindex = list.getSelectedValue().indexOf("Price:");
                            //String.substring(first, last) creates a substring from first position to the last position
                            hotel.bookRoom(true, ID, list.getSelectedValue().substring(11, priceindex - 2),
                                    startdate, enddate);
                            listModel.clear();
                            hotel.displayRoomsAvailable(startdate, enddate);
                        } catch (NullPointerException error) {
                            speakError("Error: please select a room");
                        }
                    }
                });
            }
        }
    });
    JButton reserveButton = new JButton("Display Reservations");
    reserveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            listModel.clear();
            hotel.displayCustomerBalance(ID);
            leftButton.setText("Delete Reservation");
            leftButton.setVisible(true);
            for (ActionListener al : leftButton.getActionListeners())
                leftButton.removeActionListener(al);
            leftButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    System.out.println(list.getSelectedIndex());
                    hotel.removeBookRoom(ID, list.getSelectedIndex());
                    listModel.clear();
                    hotel.displayCustomerBalance(ID);
                }
            });
        }
    });
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(roomsButton);
    buttonPanel.add(reserveButton);
    JLabel startLabel = new JLabel("Start Date: ");
    buttonPanel.add(startLabel);
    buttonPanel.add(start);
    JLabel endLabel = new JLabel("End Date: ");
    buttonPanel.add(endLabel);
    buttonPanel.add(end);
    frame.add(buttonPanel, BorderLayout.NORTH);

    //Setting some final settings for the frame itself
    frame.setPreferredSize(new Dimension(800, 600));
    frame.pack();
    frame.setVisible(true);
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent event) {
            logout();
            listModel.clear();
            frame.dispose();
        }
    });
}