Example usage for org.joda.time LocalDate minusMonths

List of usage examples for org.joda.time LocalDate minusMonths

Introduction

In this page you can find the example usage for org.joda.time LocalDate minusMonths.

Prototype

public LocalDate minusMonths(int months) 

Source Link

Document

Returns a copy of this date minus the specified number of months.

Usage

From source file:net.objectlab.kit.datecalc.joda.LocalDateIMMDateCalculator.java

License:Apache License

private LocalDate calculateIMMMonth(final boolean requestNextIMM, final LocalDate startDate, final int month) {
    int monthOffset = 0;
    LocalDate date = startDate;
    switch (month) {
    case MARCH://from   ww w.j  a v  a2  s .c  om
    case JUNE:
    case SEPTEMBER:
    case DECEMBER:
        final LocalDate immDate = calculate3rdWednesday(date);
        if (requestNextIMM && !date.isBefore(immDate)) {
            date = date.plusMonths(MONTHS_IN_QUARTER);
        } else if (!requestNextIMM && !date.isAfter(immDate)) {
            date = date.minusMonths(MONTHS_IN_QUARTER);
        }
        break;

    default:
        if (requestNextIMM) {
            monthOffset = (MONTH_IN_YEAR - month) % MONTHS_IN_QUARTER;
            date = date.plusMonths(monthOffset);
        } else {
            monthOffset = month % MONTHS_IN_QUARTER;
            date = date.minusMonths(monthOffset);
        }
        break;
    }
    return date;
}

From source file:op.allowance.PnlAllowance.java

License:Open Source License

private CollapsiblePane createCP4(final Resident resident, final LocalDate month) {
    final String key = getKey(resident, month);
    if (!cpMap.containsKey(key)) {
        cpMap.put(key, new CollapsiblePane());
        try {// w w  w . j av a  2 s .  co  m
            cpMap.get(key).setCollapsed(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }

    }
    final CollapsiblePane cpMonth = cpMap.get(key);

    if (!carrySums.containsKey(key)) {
        carrySums.put(key, AllowanceTools.getSUM(resident, SYSCalendar.eom(month)));
    }

    String title = "<html><table border=\"0\">" + "<tr>" +

            "<td width=\"520\" align=\"left\">" + monthFormatter.format(month.toDate()) + "</td>"
            + "<td width=\"200\" align=\"right\">"
            + (carrySums.get(key).compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "")
            + cf.format(carrySums.get(key))
            + (carrySums.get(key).compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>"
            + "</table>" +

            "</font></html>";

    DefaultCPTitle cptitle = new DefaultCPTitle(title, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                cpMonth.setCollapsed(!cpMonth.isCollapsed());
            } catch (PropertyVetoException pve) {
                // BAH!
            }
        }
    });

    /***
     *      ____       _       _   __  __             _   _
     *     |  _ \ _ __(_)_ __ | |_|  \/  | ___  _ __ | |_| |__
     *     | |_) | '__| | '_ \| __| |\/| |/ _ \| '_ \| __| '_ \
     *     |  __/| |  | | | | | |_| |  | | (_) | | | | |_| | | |
     *     |_|   |_|  |_|_| |_|\__|_|  |_|\___/|_| |_|\__|_| |_|
     *
     */
    final JButton btnPrintMonth = new JButton(SYSConst.icon22print2);
    btnPrintMonth.setPressedIcon(SYSConst.icon22print2Pressed);
    btnPrintMonth.setAlignmentX(Component.RIGHT_ALIGNMENT);
    btnPrintMonth.setContentAreaFilled(false);
    btnPrintMonth.setBorder(null);
    btnPrintMonth.setToolTipText(SYSTools.xx("misc.tooltips.btnprintmonth"));
    btnPrintMonth.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            if (!cashmap.containsKey(key)) {
                cashmap.put(key, AllowanceTools.getMonth(resident, month.toDate()));
            }

            final BigDecimal carry4print = AllowanceTools.getSUM(resident,
                    SYSCalendar.eom(month.minusMonths(1)));
            SYSFilesTools.print(AllowanceTools.getAsHTML(cashmap.get(key), carry4print, resident), true);
        }
    });

    cptitle.getRight().add(btnPrintMonth);

    cpMonth.setTitleLabelComponent(cptitle.getMain());
    cpMonth.setSlidingDirection(SwingConstants.SOUTH);

    cpMonth.setBackground(getBG(resident, 10));

    /***
     *           _ _      _            _                                       _   _
     *       ___| (_) ___| | _____  __| |   ___  _ __    _ __ ___   ___  _ __ | |_| |__
     *      / __| | |/ __| |/ / _ \/ _` |  / _ \| '_ \  | '_ ` _ \ / _ \| '_ \| __| '_ \
     *     | (__| | | (__|   <  __/ (_| | | (_) | | | | | | | | | | (_) | | | | |_| | | |
     *      \___|_|_|\___|_|\_\___|\__,_|  \___/|_| |_| |_| |_| |_|\___/|_| |_|\__|_| |_|
     *
     */
    cpMonth.addCollapsiblePaneListener(new CollapsiblePaneAdapter() {
        @Override
        public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) {

            cpMonth.setContentPane(createContentPanel4(resident, month));
            cpMonth.setOpaque(false);
        }
    });

    if (!cpMonth.isCollapsed()) {
        cpMonth.setContentPane(createContentPanel4(resident, month));
    }

    cpMonth.setHorizontalAlignment(SwingConstants.LEADING);
    cpMonth.setOpaque(false);

    return cpMonth;
}

From source file:op.allowance.PnlAllowance.java

License:Open Source License

private JPanel createContentPanel4(final Resident resident, LocalDate month) {
    final String key = getKey(resident, month);

    if (!contentmap.containsKey(key)) {

        JPanel pnlMonth = new JPanel(new VerticalLayout());

        pnlMonth.setBackground(getBG(resident, 11));
        pnlMonth.setOpaque(false);/*from w w w . j  a v a2s .c  o m*/

        //            final String prevKey = resident.getRID() + "-" + SYSCalendar.eom(month.minusMonths(1)).getYear() + "-" + SYSCalendar.eom(month.minusMonths(1)).getMonthOfYear();
        if (!carrySums.containsKey(key)) {
            carrySums.put(key, AllowanceTools.getSUM(resident, SYSCalendar.eom(month.minusMonths(1))));
        }

        BigDecimal rowsum = carrySums.get(key);

        if (!cashmap.containsKey(key)) {
            cashmap.put(key, AllowanceTools.getMonth(resident, month.toDate()));
        }

        JLabel lblEOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMaximumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.endofmonth") + "</td>"
                + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        pnlMonth.add(lblEOM);

        for (final Allowance allowance : cashmap.get(key)) {

            String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                    + DateFormat.getDateInstance().format(allowance.getPit()) + "</td>"
                    + "<td width=\"400\" align=\"left\">" + allowance.getText() + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "")
                    + cf.format(allowance.getAmount())
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>"
                    +

                    "</font></html>";

            DefaultCPTitle cptitle = new DefaultCPTitle(title, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

                }
            });
            cptitle.getButton().setIcon(
                    allowance.isReplaced() || allowance.isReplacement() ? SYSConst.icon22eraser : null);

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
                /***
                 *      _____    _ _ _
                 *     | ____|__| (_) |_
                 *     |  _| / _` | | __|
                 *     | |__| (_| | | |_
                 *     |_____\__,_|_|\__|
                 *
                 */
                final JButton btnEdit = new JButton(SYSConst.icon22edit3);
                btnEdit.setPressedIcon(SYSConst.icon22edit3Pressed);
                btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnEdit.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnEdit.setContentAreaFilled(false);
                btnEdit.setBorder(null);
                btnEdit.setToolTipText(SYSTools.xx("admin.residents.cash.btnedit.tooltip"));
                btnEdit.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        final JidePopup popupTX = new JidePopup();
                        popupTX.setMovable(false);
                        PnlTX pnlTX = getPnlTX(resident, allowance);
                        popupTX.setContentPane(pnlTX);
                        popupTX.removeExcludedComponent(pnlTX);
                        popupTX.setDefaultFocusComponent(pnlTX);

                        popupTX.setOwner(btnEdit);
                        GUITools.showPopup(popupTX, SwingConstants.WEST);

                    }
                });
                cptitle.getRight().add(btnEdit);
                // you can edit your own entries or you are a manager. once they are replaced or a replacement record, its over.
                btnEdit.setEnabled((OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, internalClassID)
                        || allowance.getUser().equals(OPDE.getLogin().getUser())) && !allowance.isReplaced()
                        && !allowance.isReplacement());

                /***
                 *      _   _           _         _______  __
                 *     | | | |_ __   __| | ___   |_   _\ \/ /
                 *     | | | | '_ \ / _` |/ _ \    | |  \  /
                 *     | |_| | | | | (_| | (_) |   | |  /  \
                 *      \___/|_| |_|\__,_|\___/    |_| /_/\_\
                 *
                 */
                final JButton btnUndoTX = new JButton(SYSConst.icon22undo);
                btnUndoTX.setPressedIcon(SYSConst.icon22Pressed);
                btnUndoTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnUndoTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnUndoTX.setContentAreaFilled(false);
                btnUndoTX.setBorder(null);
                btnUndoTX.setToolTipText(SYSTools.xx("admin.residents.cash.btnundotx.tooltip"));
                btnUndoTX.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        new DlgYesNo(
                                SYSTools.xx("misc.questions.undo1") + "<br/><i>" + "<br/><i>"
                                        + allowance.getText() + "&nbsp;" + cf.format(allowance.getAmount())
                                        + "</i><br/>" + SYSTools.xx("misc.questions.undo2"),
                                SYSConst.icon48undo, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();

                                                Allowance myOldAllowance = em.merge(allowance);
                                                Allowance myCancelAllowance = em
                                                        .merge(new Allowance(myOldAllowance));
                                                em.lock(em.merge(myOldAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);
                                                em.lock(myOldAllowance, LockModeType.OPTIMISTIC);
                                                myOldAllowance.setReplacedBy(myCancelAllowance,
                                                        em.merge(OPDE.getLogin().getUser()));

                                                em.getTransaction().commit();

                                                DateTime txDate = new DateTime(myCancelAllowance.getPit());

                                                final String keyMonth = myCancelAllowance.getResident().getRID()
                                                        + "-" + txDate.getYear() + "-"
                                                        + txDate.getMonthOfYear();
                                                contentmap.remove(keyMonth);
                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(allowance);
                                                cashmap.get(keyMonth).add(myOldAllowance);
                                                cashmap.get(keyMonth).add(myCancelAllowance);
                                                Collections.sort(cashmap.get(keyMonth));

                                                updateCarrySums(myCancelAllowance);

                                                createCP4(myCancelAllowance.getResident());

                                                try {
                                                    cpMap.get(keyMonth).setCollapsed(false);
                                                } catch (PropertyVetoException e) {
                                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                                }

                                                buildPanel();

                                            } catch (OptimisticLockException ole) {
                                                OPDE.warn(ole);
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                if (ole.getMessage()
                                                        .indexOf("Class> entity.info.Resident") > -1) {
                                                    OPDE.getMainframe().emptyFrame();
                                                    OPDE.getMainframe().afterLogin();
                                                }
                                                OPDE.getDisplayManager()
                                                        .addSubMessage(DisplayManager.getLockMessage());
                                            } catch (Exception e) {
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                OPDE.fatal(e);
                                            } finally {
                                                em.close();
                                            }
                                        }
                                    }
                                });
                    }
                });
                cptitle.getRight().add(btnUndoTX);
                btnUndoTX.setEnabled(!allowance.isReplaced() && !allowance.isReplacement());
            }

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, internalClassID)) {
                /***
                 *      ____       _      _
                 *     |  _ \  ___| | ___| |_ ___
                 *     | | | |/ _ \ |/ _ \ __/ _ \
                 *     | |_| |  __/ |  __/ ||  __/
                 *     |____/ \___|_|\___|\__\___|
                 *
                 */
                final JButton btnDelete = new JButton(SYSConst.icon22delete);
                btnDelete.setPressedIcon(SYSConst.icon22deletePressed);
                btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnDelete.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnDelete.setContentAreaFilled(false);
                btnDelete.setBorder(null);
                btnDelete.setToolTipText(SYSTools.xx("admin.residents.cash.btndelete.tooltip"));
                btnDelete.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        new DlgYesNo(
                                SYSTools.xx("misc.questions.delete1") + "<br/><i>" + allowance.getText()
                                        + "&nbsp;" + cf.format(allowance.getAmount()) + "</i><br/>"
                                        + SYSTools.xx("misc.questions.delete2"),
                                SYSConst.icon48delete, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();
                                                Allowance myAllowance = em.merge(allowance);
                                                em.lock(em.merge(myAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);

                                                Allowance theOtherOne = null;
                                                // Check for special cases
                                                if (myAllowance.isReplacement()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacementFor());
                                                    theOtherOne.setReplacedBy(null);
                                                    theOtherOne.setEditedBy(null);
                                                    myAllowance.setEditPit(null);
                                                }
                                                if (myAllowance.isReplaced()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacedBy());
                                                    theOtherOne.setReplacementFor(null);
                                                }

                                                em.remove(myAllowance);
                                                em.getTransaction().commit();

                                                DateTime txDate = new DateTime(myAllowance.getPit());
                                                final String keyMonth = myAllowance.getResident().getRID() + "-"
                                                        + txDate.getYear() + "-" + txDate.getMonthOfYear();

                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(myAllowance);
                                                if (theOtherOne != null) {
                                                    cashmap.get(keyMonth).remove(theOtherOne);
                                                    cashmap.get(keyMonth).add(theOtherOne);
                                                    Collections.sort(cashmap.get(keyMonth));
                                                }

                                                // only to update the carrysums. myAllowance will be discarded soon.
                                                myAllowance.setAmount(myAllowance.getAmount().negate());
                                                updateCarrySums(myAllowance);

                                                createCP4(myAllowance.getResident());

                                                try {
                                                    if (cpMap.containsKey(keyMonth)) {
                                                        cpMap.get(keyMonth).setCollapsed(false);
                                                    }
                                                } catch (PropertyVetoException e) {
                                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                                }

                                                buildPanel();
                                            } catch (OptimisticLockException ole) {
                                                OPDE.warn(ole);
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                if (ole.getMessage()
                                                        .indexOf("Class> entity.info.Resident") > -1) {
                                                    OPDE.getMainframe().emptyFrame();
                                                    OPDE.getMainframe().afterLogin();
                                                }
                                                OPDE.getDisplayManager()
                                                        .addSubMessage(DisplayManager.getLockMessage());
                                            } catch (Exception e) {
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                OPDE.fatal(e);
                                            } finally {
                                                em.close();
                                            }
                                        }
                                    }
                                });
                    }
                });
                cptitle.getRight().add(btnDelete);
            }
            pnlMonth.add(cptitle.getMain());
            linemap.put(allowance, cptitle.getMain());

            rowsum = rowsum.subtract(allowance.getAmount());
        }

        JLabel lblBOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMinimumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.startofmonth")
                + "</td>" + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        lblBOM.setBackground(getBG(resident, 11));
        pnlMonth.add(lblBOM);
        contentmap.put(key, pnlMonth);
    }

    return contentmap.get(key);
}

From source file:op.allowance.PnlAllowance.java

License:Open Source License

private void updateCarrySums(Resident resident, LocalDate pit, BigDecimal amount) {
    String prevKey = getKey(resident, SYSCalendar.eom(pit.minusMonths(1)));
    if (!carrySums.containsKey(prevKey)) {
        carrySums.put(prevKey, AllowanceTools.getSUM(resident, SYSCalendar.eom(pit).minusMonths(1)));
    }//from  w w w . j  av  a2  s. c om

    // update carrysums
    for (LocalDate month = SYSCalendar.eom(pit); month
            .compareTo(SYSCalendar.eoy(new LocalDate())) <= 0; month = SYSCalendar.eom(month.plusMonths(1))) {
        OPDE.debug(month.toString("yyyy-MM-dd"));
        final String key = getKey(resident, month);

        if (!carrySums.containsKey(key)) {
            prevKey = getKey(resident, SYSCalendar.eom(month.minusMonths(1)));
            carrySums.put(key, carrySums.get(prevKey).add(amount));
        } else {
            carrySums.put(key, carrySums.get(key).add(amount));
        }

        contentmap.remove(key);
    }

    // fix minmax interval
    Interval myMinMax = new Interval(minmax.get(resident).getFirst().toDateTimeAtStartOfDay(),
            SYSCalendar.eod(minmax.get(resident).getSecond()));
    if (myMinMax.isBefore(pit.toDateTimeAtCurrentTime())) {
        minmax.put(resident, new Pair(minmax.get(resident).getFirst(), SYSCalendar.eom(pit)));
    } else if (myMinMax.isAfter(pit.toDateTimeAtCurrentTime())) {
        minmax.put(resident, new Pair(SYSCalendar.bom(pit), minmax.get(resident).getSecond()));
    }

}

From source file:org.activiti.dmn.engine.impl.mvel.extension.DateUtil.java

License:Apache License

public static Date subtractDate(Date startDate, Integer years, Integer months, Integer days) {

    LocalDate currentDate = new LocalDate(startDate);

    currentDate = currentDate.minusYears(years);
    currentDate = currentDate.minusMonths(months);
    currentDate = currentDate.minusDays(days);

    return currentDate.toDate();
}

From source file:org.alexlg.bankit.controllers.AccountController.java

License:Open Source License

/**
 * Calculate the first day of the history. If the current day is after the 7th day of the month,
 * the return date will be the 1st of the current month. Otherwise, the return date
 * will be the 1st of the previous month.
 * @return First history day/*from   w  w w . j  av  a 2s.  c  om*/
 */
protected LocalDate calculateFirstHistoDay() {
    LocalDate date = new LocalDate();
    if (date.getDayOfMonth() > 7) {
        return date.withDayOfMonth(1);
    } else {
        return date.minusMonths(1).withDayOfMonth(1);
    }
}

From source file:org.apache.fineract.portfolio.loanaccount.loanschedule.domain.DefaultScheduledDateGenerator.java

License:Apache License

@Override
public LocalDate idealDisbursementDateBasedOnFirstRepaymentDate(
        final PeriodFrequencyType repaymentPeriodFrequencyType, final int repaidEvery,
        final LocalDate firstRepaymentDate) {

    LocalDate idealDisbursementDate = null;

    switch (repaymentPeriodFrequencyType) {
    case DAYS://from   www .  j a  v a2 s.  co  m
        idealDisbursementDate = firstRepaymentDate.minusDays(repaidEvery);
        break;
    case WEEKS:
        idealDisbursementDate = firstRepaymentDate.minusWeeks(repaidEvery);
        break;
    case MONTHS:
        idealDisbursementDate = firstRepaymentDate.minusMonths(repaidEvery);
        break;
    case YEARS:
        idealDisbursementDate = firstRepaymentDate.minusYears(repaidEvery);
        break;
    case INVALID:
        break;
    }

    return idealDisbursementDate;
}

From source file:org.apache.niolex.common.joda.Joda.java

License:Apache License

/**
 * @param args//from  w ww .  j a  v  a  2s .c  o  m
 */
public static void main(String[] args) {
    Locale.setDefault(Locale.ENGLISH);
    // --- ?
    LocalDate now = new LocalDate();
    LocalDate lastDayOfPreviousMonth = now.minusMonths(1).dayOfMonth().withMaximumValue();
    // - Print
    SystemUtil.println(lastDayOfPreviousMonth.toString());

    // ---  11 ?
    LocalDate electionDate = now.monthOfYear().setCopy(11) // November
            .dayOfMonth() // Access Day Of Month Property
            .withMinimumValue() // Get its minimum value
            .plusDays(6) // Add 6 days
            .dayOfWeek() // Access Day Of Week Property
            .setCopy("Monday") // Set to Monday (it will round down)
            .plusDays(1); // Gives us Tuesday
    // - Print
    SystemUtil.println(electionDate.toString());

    // --- ??
    LocalDate then = now.plusWeeks(2);
    // - Print
    SystemUtil.println(then.toString());
}

From source file:org.estatio.app.index.maint.IndexValueMaintLineItem.java

License:Apache License

private String check() {

    @SuppressWarnings("rawtypes")
    List lineItemObjs = bulkInteractionContext.getDomainObjects();
    @SuppressWarnings("unchecked")
    List<IndexValueMaintLineItem> lineItems = lineItemObjs;

    // ensure items to process
    if (lineItems.isEmpty()) {
        return "No rows in spreadsheet";
    }//from w w w .  j a v  a2s  . c  o  m

    // ensure all rows for a single index
    String reference = null;
    for (int i = 0; i < lineItems.size(); i++) {
        IndexValueMaintLineItem lineItem = lineItems.get(i);
        String eachReference = lineItem.getReference();
        if (reference == null) {
            reference = eachReference;
        } else {
            if (!Objects.equal(reference, eachReference)) {
                return "Row " + (i + 1) + ": all rows must be for same index reference";
            }
        }
    }

    // ensure valueStartDates are sequential
    LocalDate previousValueStartDate = null;
    LocalDate eachValueStartDate;
    for (int i = 0; i < lineItems.size(); i++) {
        IndexValueMaintLineItem lineItem = lineItems.get(i);

        eachValueStartDate = lineItem.getValueStartDate();
        if (previousValueStartDate != null) {
            if (!Objects.equal(eachValueStartDate.minusMonths(1), previousValueStartDate)) {
                return "Row " + (i + 1) + ": all rows must be for sequential; found "
                        + previousValueStartDate.toString("yyyy/MM/dd") + " and "
                        + eachValueStartDate.toString("yyyy/MM/dd");
            }
        }
        previousValueStartDate = eachValueStartDate;
    }

    // if existing index, ensure valueStartDate is:
    // * either for an existing month,
    // * or follows on from previous by no more than 1 month
    Index index = indices.findIndex(reference);
    boolean existingIndex = index != null;
    scratchpad.put("index", index);
    if (existingIndex) {
        LocalDate firstValueStartDate = null;
        for (IndexValueMaintLineItem lineItem : lineItems) {
            firstValueStartDate = lineItem.getValueStartDate();
            scratchpad.put("firstValueStartDate", firstValueStartDate);
            break;
        }

        IndexValue existingValue = indexValues.findIndexValueByIndexAndStartDate(index, firstValueStartDate);
        if (existingValue == null) {
            LocalDate previousMonthValueStartDate = firstValueStartDate.minusMonths(1);
            IndexValue previousValue = indexValues.findIndexValueByIndexAndStartDate(index,
                    previousMonthValueStartDate);
            if (previousValue == null) {
                IndexValue last = indexValues.findLastByIndex(index);
                if (last != null) {
                    return "First row (" + firstValueStartDate.toString("yyyy/MM/dd")
                            + ") must be an existing month or " + "for the 1 month after last ("
                            + last.getStartDate().toString("yyyy/MM/dd") + ")";
                }
            } else {
                scratchpad.put("previousBase", previousValue.getIndexBase());
            }
        } else {
            scratchpad.put("previousBase", existingValue.getIndexBase());
        }
    }

    // ensure that baseStartDate and baseFactors change in step
    LocalDate previousBaseStartDate = null;
    BigDecimal previousBaseFactor = null;
    for (int i = 0; i < lineItems.size(); i++) {
        IndexValueMaintLineItem lineItem = lineItems.get(i);

        LocalDate eachBaseStartDate = lineItem.getBaseStartDate();
        BigDecimal eachBaseFactor = lineItem.getBaseFactor();
        if (previousBaseStartDate != null || previousBaseFactor != null) {
            if (Objects.equal(previousBaseStartDate, eachBaseStartDate)
                    && !Objects.equal(previousBaseFactor, eachBaseFactor)) {
                return "Base factors can only change if base start date changes; " + "baseStartDate: "
                        + eachBaseStartDate.toString("yyyy/MM/dd") + ", baseFactor: " + eachBaseFactor;
            }
        }
        previousBaseStartDate = eachBaseStartDate;
        previousBaseFactor = eachBaseFactor;
    }
    return null;
}

From source file:org.estatio.services.clock.ClockService.java

License:Apache License

static LocalDate beginningOfQuarter(final LocalDate date) {
    final LocalDate beginningOfMonth = beginningOfMonth(date);
    final int monthOfYear = beginningOfMonth.getMonthOfYear();
    final int quarter = (monthOfYear - 1) / MONTHS_IN_QUARTER; // 0, 1, 2, 3
    final int monthStartOfQuarter = quarter * MONTHS_IN_QUARTER + 1;
    return beginningOfMonth.minusMonths(monthOfYear - monthStartOfQuarter);
}