Example usage for org.joda.time LocalDateTime plusMonths

List of usage examples for org.joda.time LocalDateTime plusMonths

Introduction

In this page you can find the example usage for org.joda.time LocalDateTime plusMonths.

Prototype

public LocalDateTime plusMonths(int months) 

Source Link

Document

Returns a copy of this datetime plus the specified number of months.

Usage

From source file:com.axelor.apps.crm.service.EventService.java

License:Open Source License

@Transactional
public void addRecurrentEventsByMonths(Event event, int periodicity, int endType, int repetitionsNumber,
        LocalDate endDate, int monthRepeatType) {
    Event lastEvent = event;/*ww w  .  j  a  va2s.  co m*/
    if (monthRepeatType == 1) {
        int dayOfMonth = event.getStartDateTime().getDayOfMonth();
        if (endType == 1) {
            int repeated = 0;
            while (repeated != repetitionsNumber) {
                Event copy = eventRepo.copy(lastEvent, false);
                copy.setParentEvent(lastEvent);
                if (copy.getStartDateTime().plusMonths(periodicity).dayOfMonth()
                        .getMaximumValue() >= dayOfMonth) {
                    copy.setStartDateTime(copy.getStartDateTime().plusMonths(periodicity));
                    copy.setEndDateTime(copy.getEndDateTime().plusMonths(periodicity));
                    eventRepo.save(copy);
                    repeated++;
                    lastEvent = copy;
                }
            }
        } else {
            while (!lastEvent.getStartDateTime().plusMonths(periodicity).isAfter(endDate)) {
                Event copy = eventRepo.copy(lastEvent, false);
                copy.setParentEvent(lastEvent);
                if (copy.getStartDateTime().plusMonths(periodicity).dayOfMonth()
                        .getMaximumValue() >= dayOfMonth) {
                    copy.setStartDateTime(copy.getStartDateTime().plusMonths(periodicity));
                    copy.setEndDateTime(copy.getEndDateTime().plusMonths(periodicity));
                    eventRepo.save(copy);
                    lastEvent = copy;
                }
            }
        }
    }

    else {
        int dayOfWeek = event.getStartDateTime().getDayOfWeek();
        int positionInMonth = 0;
        if (event.getStartDateTime().getDayOfMonth() % 7 == 0) {
            positionInMonth = event.getStartDateTime().getDayOfMonth() / 7;
        } else {
            positionInMonth = (event.getStartDateTime().getDayOfMonth() / 7) + 1;
        }

        if (endType == 1) {
            int repeated = 0;
            while (repeated != repetitionsNumber) {
                Event copy = eventRepo.copy(lastEvent, false);
                copy.setParentEvent(lastEvent);
                LocalDateTime nextDateTime = new LocalDateTime(copy.getStartDateTime());
                nextDateTime.plusMonths(periodicity);
                int nextDayOfWeek = nextDateTime.getDayOfWeek();
                if (nextDayOfWeek > dayOfWeek) {
                    nextDateTime.minusDays(nextDayOfWeek - dayOfWeek);
                } else {
                    nextDateTime.plusDays(dayOfWeek - nextDayOfWeek);
                }
                int nextPositionInMonth = 0;
                if (event.getStartDateTime().getDayOfMonth() % 7 == 0) {
                    nextPositionInMonth = event.getStartDateTime().getDayOfMonth() / 7;
                } else {
                    nextPositionInMonth = (event.getStartDateTime().getDayOfMonth() / 7) + 1;
                }
                if (nextPositionInMonth > positionInMonth) {
                    nextDateTime.minusWeeks(nextPositionInMonth - positionInMonth);
                } else {
                    nextDateTime.plusWeeks(positionInMonth - nextPositionInMonth);
                }
                Duration dur = new Duration(copy.getStartDateTime().toDateTime(),
                        copy.getEndDateTime().toDateTime());
                copy.setStartDateTime(nextDateTime);
                copy.setEndDateTime(nextDateTime.plus(dur));
                eventRepo.save(copy);
                repeated++;
                lastEvent = copy;
            }
        } else {
            LocalDateTime nextDateTime = new LocalDateTime(lastEvent.getStartDateTime());
            nextDateTime.plusMonths(periodicity);
            int nextDayOfWeek = nextDateTime.getDayOfWeek();
            if (nextDayOfWeek > dayOfWeek) {
                nextDateTime.minusDays(nextDayOfWeek - dayOfWeek);
            } else {
                nextDateTime.plusDays(dayOfWeek - nextDayOfWeek);
            }
            int nextPositionInMonth = 0;
            if (event.getStartDateTime().getDayOfMonth() % 7 == 0) {
                nextPositionInMonth = event.getStartDateTime().getDayOfMonth() / 7;
            } else {
                nextPositionInMonth = (event.getStartDateTime().getDayOfMonth() / 7) + 1;
            }
            if (nextPositionInMonth > positionInMonth) {
                nextDateTime.minusWeeks(nextPositionInMonth - positionInMonth);
            } else {
                nextDateTime.plusWeeks(positionInMonth - nextPositionInMonth);
            }
            while (!nextDateTime.isAfter(endDate)) {
                Event copy = eventRepo.copy(lastEvent, false);
                copy.setParentEvent(lastEvent);

                Duration dur = new Duration(copy.getStartDateTime().toDateTime(),
                        copy.getEndDateTime().toDateTime());
                copy.setStartDateTime(nextDateTime);
                copy.setEndDateTime(nextDateTime.plus(dur));
                eventRepo.save(copy);
                lastEvent = copy;

                nextDateTime = new LocalDateTime(lastEvent.getStartDateTime());
                nextDateTime.plusMonths(periodicity);
                nextDayOfWeek = nextDateTime.getDayOfWeek();
                if (nextDayOfWeek > dayOfWeek) {
                    nextDateTime.minusDays(nextDayOfWeek - dayOfWeek);
                } else {
                    nextDateTime.plusDays(dayOfWeek - nextDayOfWeek);
                }
                nextPositionInMonth = 0;
                if (event.getStartDateTime().getDayOfMonth() % 7 == 0) {
                    nextPositionInMonth = event.getStartDateTime().getDayOfMonth() / 7;
                } else {
                    nextPositionInMonth = (event.getStartDateTime().getDayOfMonth() / 7) + 1;
                }
                if (nextPositionInMonth > positionInMonth) {
                    nextDateTime.minusWeeks(nextPositionInMonth - positionInMonth);
                } else {
                    nextDateTime.plusWeeks(positionInMonth - nextPositionInMonth);
                }
            }
        }
    }
}

From source file:com.axelor.csv.script.ImportDateTime.java

License:Open Source License

public LocalDateTime updateMonth(LocalDateTime dateTime, String month) {
    if (!Strings.isNullOrEmpty(month)) {
        Matcher matcher = patternMonth.matcher(month);
        if (matcher.find()) {
            Integer months = Integer.parseInt(matcher.group());
            if (month.startsWith("+"))
                dateTime = dateTime.plusMonths(months);
            else if (month.startsWith("-"))
                dateTime = dateTime.minusMonths(months);
            else/*from   w w w .  j  a va 2 s  .c  om*/
                dateTime = dateTime.withMonthOfYear(months);
        }
    }
    return dateTime;
}

From source file:com.effektif.workflow.api.model.NextRelativeTime.java

License:Apache License

@Override
public LocalDateTime resolve(LocalDateTime base) {
    LocalDateTime time = null;
    if (HOUR_OF_DAY.equals(indexUnit)) {
        time = base.withTime(index, 0, 0, 0);
        if (!time.isAfter(base)) {
            return time.plusDays(1);
        }/*from  w w  w.jav  a  2 s .c  o  m*/
    } else if (DAY_OF_WEEK.equals(indexUnit)) {
        time = base.withDayOfWeek(index).withTime(0, 0, 0, 0);
        if (!time.isAfter(base)) {
            time = time.plusWeeks(1);
        }
    } else if (DAY_OF_MONTH.equals(indexUnit)) {
        time = base.withDayOfMonth(index).withTime(0, 0, 0, 0);
        if (!time.isAfter(base)) {
            time = time.plusMonths(1);
        }
    }
    if (atHour != null) {
        time = time.withTime(atHour, atMinute != null ? atMinute : 0, 0, 0);
    }
    return time;
}

From source file:com.helger.peppol.smpserver.ui.secure.PageSecureTasks.java

License:Apache License

@Override
protected void fillContent(@Nonnull final WebPageExecutionContext aWPEC) {
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final Locale aDisplayLocale = aWPEC.getDisplayLocale();
    final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
    final ISMPServiceInformationManager aServiceInfoMgr = SMPMetaManager.getServiceInformationMgr();
    final ISMPRedirectManager aRedirectMgr = SMPMetaManager.getRedirectMgr();
    final LocalDateTime aNowDT = PDTFactory.getCurrentLocalDateTime();
    final LocalDateTime aNowPlusDT = aNowDT.plusMonths(3);

    aNodeList.addChild(new BootstrapInfoBox().addChild(
            "This page tries to identify upcoming tasks and potential problems in the SMP configuration. It is meant to highlight immediate and upcoming action items as well as potential misconfiguration."));

    final HCOL aOL = new HCOL();

    // check certificate configuration
    {/*from   w ww .j a va2  s  .  co m*/
        final KeyLoadingResult aKeyLoadingResult = KeyLoadingResult.loadConfiguredKey();
        if (aKeyLoadingResult.isFailure())
            aOL.addItem(_createError("Problem with the certificate configuration"),
                    new HCDiv().addChild(aKeyLoadingResult.getErrorMessage()));
    }

    // Check SML configuration
    {
        if (!RegistrationHookFactory.isSMLConnectionActive())
            aOL.addItem(_createWarning("The connection to the SML is not active."), new HCDiv().addChild(
                    "All creations and deletions of service groups needs to be repeated when the SML connection is active!"));
    }

    // check service groups and redirects
    {
        final Collection<? extends ISMPServiceGroup> aServiceGroups = aServiceGroupMgr.getAllSMPServiceGroups();
        final Collection<? extends ISMPRedirect> aRedirects = aRedirectMgr.getAllSMPRedirects();
        if (aServiceGroups.isEmpty() && aRedirects.isEmpty()) {
            aOL.addItem(_createWarning(
                    "Neither a service group nor a redirect is configured. This SMP is currently empty."));
        } else {
            // For all service groups
            for (final ISMPServiceGroup aServiceGroup : CollectionHelper.getSorted(aServiceGroups,
                    new ComparatorSMPServiceGroup())) {
                final HCUL aULPerSG = new HCUL();
                final Collection<? extends ISMPServiceInformation> aServiceInfos = aServiceInfoMgr
                        .getAllSMPServiceInformationsOfServiceGroup(aServiceGroup);
                if (aServiceInfos.isEmpty()) {
                    aULPerSG.addItem(_createWarning("No endpoint is configured for this service group."));
                } else {
                    for (final ISMPServiceInformation aServiceInfo : aServiceInfos) {
                        final HCUL aULPerDocType = new HCUL();
                        final Collection<? extends ISMPProcess> aProcesses = aServiceInfo.getAllProcesses();
                        for (final ISMPProcess aProcess : aProcesses) {
                            final HCUL aULPerProcess = new HCUL();
                            final Collection<? extends ISMPEndpoint> aEndpoints = aProcess.getAllEndpoints();
                            for (final ISMPEndpoint aEndpoint : aEndpoints) {
                                final HCUL aULPerEndpoint = new HCUL();

                                final ESMPTransportProfile eTransportProfile = ESMPTransportProfile
                                        .getFromIDOrNull(aEndpoint.getTransportProfile());
                                if (eTransportProfile == null)
                                    aULPerEndpoint.addItem(_createWarning(
                                            "The endpoint uses the non-standard transport profile '"
                                                    + aEndpoint.getTransportProfile() + "'."));

                                if (aEndpoint.getServiceActivationDateTime() != null) {
                                    if (aEndpoint.getServiceActivationDateTime().isAfter(aNowDT))
                                        aULPerEndpoint.addItem(_createWarning(
                                                "The endpoint is not yet active. It will be active from "
                                                        + PDTToString.getAsString(
                                                                aEndpoint.getServiceActivationDateTime(),
                                                                aDisplayLocale)
                                                        + "."));
                                }

                                if (aEndpoint.getServiceExpirationDateTime() != null) {
                                    if (aEndpoint.getServiceExpirationDateTime().isBefore(aNowDT))
                                        aULPerEndpoint.addItem(_createError(
                                                "The endpoint is not longer active. It was valid until "
                                                        + PDTToString.getAsString(
                                                                aEndpoint.getServiceExpirationDateTime(),
                                                                aDisplayLocale)
                                                        + "."));
                                    else if (aEndpoint.getServiceExpirationDateTime().isBefore(aNowPlusDT))
                                        aULPerEndpoint.addItem(_createWarning(
                                                "The endpoint will be inactive soon. It is only valid until "
                                                        + PDTToString.getAsString(
                                                                aEndpoint.getServiceExpirationDateTime(),
                                                                aDisplayLocale)
                                                        + "."));
                                }

                                X509Certificate aX509Cert = null;
                                try {
                                    aX509Cert = CertificateHelper
                                            .convertStringToCertficate(aEndpoint.getCertificate());
                                } catch (final CertificateException ex) {
                                    // Ignore
                                }
                                if (aX509Cert == null)
                                    aULPerEndpoint.addItem(_createError(
                                            "The X.509 certificate configured at the endpoint is invalid and could not be interpreted as a certificate."));
                                else {
                                    final LocalDateTime aNotBefore = PDTFactory
                                            .createLocalDateTime(aX509Cert.getNotBefore());
                                    if (aNotBefore.isAfter(aNowDT))
                                        aULPerEndpoint.addItem(_createError(
                                                "The endpoint certificate is not yet active. It will be active from "
                                                        + PDTToString.getAsString(aNotBefore, aDisplayLocale)
                                                        + "."));

                                    final LocalDateTime aNotAfter = PDTFactory
                                            .createLocalDateTime(aX509Cert.getNotAfter());
                                    if (aNotAfter.isBefore(aNowDT))
                                        aULPerEndpoint.addItem(_createError(
                                                "The endpoint certificate is already expired. It was valid until "
                                                        + PDTToString.getAsString(aNotAfter, aDisplayLocale)
                                                        + "."));
                                    else if (aNotAfter.isBefore(aNowPlusDT))
                                        aULPerEndpoint.addItem(_createWarning(
                                                "The endpoint certificate will expire soon. It is only valid until "
                                                        + PDTToString.getAsString(aNotAfter, aDisplayLocale)
                                                        + "."));
                                }

                                // Show per endpoint errors
                                if (aULPerEndpoint.hasChildren())
                                    aULPerProcess
                                            .addItem(
                                                    new HCDiv().addChild("Transport profile ")
                                                            .addChild(new HCCode()
                                                                    .addChild(aEndpoint.getTransportProfile())),
                                                    aULPerEndpoint);
                            }
                            // Show per process errors
                            if (aULPerProcess.hasChildren())
                                aULPerDocType.addItem(new HCDiv().addChild("Process ")
                                        .addChild(new HCCode().addClass(CUICoreCSS.CSS_CLASS_NOWRAP)
                                                .addChild(aProcess.getProcessIdentifier().getURIEncoded())),
                                        aULPerProcess);
                        }
                        // Show per document type errors
                        if (aULPerDocType.hasChildren())
                            aULPerSG.addItem(new HCDiv().addChild("Document type ")
                                    .addChild(new HCCode().addClass(CUICoreCSS.CSS_CLASS_NOWRAP).addChild(
                                            aServiceInfo.getDocumentTypeIdentifier().getURIEncoded())),
                                    aULPerDocType);
                    }
                }

                // Show per service group errors
                if (aULPerSG.hasChildren())
                    aOL.addItem(
                            new HCDiv().addChild("Service group ")
                                    .addChild(new HCCode()
                                            .addChild(aServiceGroup.getParticpantIdentifier().getURIEncoded())),
                            aULPerSG);
            }
        }
    }

    // Show results
    if (aOL.hasChildren()) {
        aNodeList.addChild(
                new BootstrapWarnBox().addChild("The following list of tasks and problems were identified:"));
        aNodeList.addChild(aOL);
    } else
        aNodeList.addChild(new BootstrapSuccessBox().addChild("Great job, no tasks or problems identified!"));
}

From source file:control.Xray.java

public void fillDatesInEndDate(ComboBox cEnd, ComboBox cStart, int monthsforward) {
    //Fyld datoer ind i comboboks til start og slutdato:
    LocalDateTime now = new LocalDateTime(cStart.getValue());
    LocalDateTime oneMonthForward = now.plusMonths(monthsforward);
    ArrayList<LocalDateTime> startDates = Xray.getInstance().getDatesInPeriod(now.plusDays(1), oneMonthForward);
    cEnd.getItems().clear();/*  w  w  w. j a  v  a  2  s .  co  m*/
    for (int i = 0; i < startDates.size(); i++) {
        cEnd.getItems().add(startDates.get(i));
    }
    cEnd.getSelectionModel().selectFirst();
}

From source file:ee.ut.soras.ajavtV2.mudel.ajavaljend.arvutus.SemLeidmiseAbimeetodid.java

License:Open Source License

/**
 *   Rakendab yldistatud Baldwini akent, et leida hetkele <tt>currentDateTime</tt> l2himat 
 *  ajahetke, mis vastab tingimustele <tt>field == soughtValue</tt>. Kui tingimustele vastav
 *  hetk j22b v2lja Baldwini akna raamidest, toimib kui tavaline SET operatsioon, omistades
 *  <tt>field := soughtValue</tt> ajahetke <tt>currentDateTime</tt> raames.
 *  <p>/*  w w w .  j  a  v a2 s  . co  m*/
 *  Praegu on implementeeritud ainult granulaarsuste 
 *  <tt>DAY_OF_WEEK</tt>, <tt>MONTH</tt>, <tt>YEAR_OF_CENTURY</tt>  
 *  toetus. 
    *  <p>
 *  <i>What's the Date? High Accuracy Interpretation of Weekday Name,</i> Dale, Mazur (2009)
 */
public static LocalDateTime applyBaldwinWindow(Granulaarsus field, LocalDateTime currentDateTime,
        int soughtValue) {
    // ---------------------------------
    //  DAY_OF_WEEK
    // ---------------------------------      
    if (field == Granulaarsus.DAY_OF_WEEK && DateTimeConstants.MONDAY <= soughtValue
            && soughtValue <= DateTimeConstants.SUNDAY) {
        int currentDayOfWeek = currentDateTime.getDayOfWeek();
        int addToCurrent = 0;
        // 1) Vaatame eelnevat 3-e p&auml;eva
        while (addToCurrent > -4) {
            if (currentDayOfWeek == soughtValue) {
                return currentDateTime.plusDays(addToCurrent);
            }
            currentDayOfWeek--;
            if (currentDayOfWeek < DateTimeConstants.MONDAY) {
                currentDayOfWeek = DateTimeConstants.SUNDAY;
            }
            addToCurrent--;
        }
        // 2) Vaatame jargnevat 3-e p&auml;eva
        currentDayOfWeek = currentDateTime.getDayOfWeek();
        addToCurrent = 0;
        while (addToCurrent < 4) {
            if (currentDayOfWeek == soughtValue) {
                return currentDateTime.plusDays(addToCurrent);
            }
            currentDayOfWeek++;
            if (currentDayOfWeek > DateTimeConstants.SUNDAY) {
                currentDayOfWeek = DateTimeConstants.MONDAY;
            }
            addToCurrent++;
        }
    }
    // ---------------------------------
    //  MONTH
    // ---------------------------------
    if (field == Granulaarsus.MONTH && DateTimeConstants.JANUARY <= soughtValue
            && soughtValue <= DateTimeConstants.DECEMBER) {
        int currentMonth = currentDateTime.getMonthOfYear();
        int addToCurrent = 0;
        // 1) Vaatame eelnevat 5-e kuud
        while (addToCurrent > -6) {
            if (currentMonth == soughtValue) {
                return currentDateTime.plusMonths(addToCurrent);
            }
            currentMonth--;
            if (currentMonth < DateTimeConstants.JANUARY) {
                currentMonth = DateTimeConstants.DECEMBER;
            }
            addToCurrent--;
        }
        // 2) Vaatame jargnevat 5-e kuud
        currentMonth = currentDateTime.getMonthOfYear();
        addToCurrent = 0;
        while (addToCurrent < 6) {
            if (currentMonth == soughtValue) {
                return currentDateTime.plusMonths(addToCurrent);
            }
            currentMonth++;
            if (currentMonth > DateTimeConstants.DECEMBER) {
                currentMonth = DateTimeConstants.JANUARY;
            }
            addToCurrent++;
        }
        // Kui otsitav kuu j2i aknast v2lja, k2sitleme seda kui "selle aasta" otsitud kuud
        return currentDateTime.withMonthOfYear(soughtValue);
    }
    // ---------------------------------
    //  YEAR_OF_CENTURY
    // ---------------------------------
    if (field == Granulaarsus.YEAR_OF_CENTURY && 0 <= soughtValue && soughtValue <= 99) {
        // API tunnistab vrtuseid vahemikust 1 kuni 100
        if (soughtValue == 0) {
            soughtValue = 100;
        }
        int currentYear = currentDateTime.getYearOfCentury();
        int addToCurrent = 0;
        // 1) Vaatame eelnevat 4-a aastakymmet 
        while (addToCurrent > -49) {
            if (currentYear == soughtValue) {
                return currentDateTime.plusYears(addToCurrent);
            }
            currentYear--;
            if (currentYear < 1) {
                currentYear = 100;
            }
            addToCurrent--;
        }
        // 2) Vaatame jargnevat 4-a aastakymmet
        currentYear = currentDateTime.getYearOfCentury();
        addToCurrent = 0;
        while (addToCurrent < 49) {
            if (currentYear == soughtValue) {
                return currentDateTime.plusYears(addToCurrent);
            }
            currentYear++;
            if (currentYear > 100) {
                currentYear = 1;
            }
            addToCurrent++;
        }
        // Kui otsitav kuu j2i aknast v2lja, k2sitleme seda kui "selle sajandi" otsitud aastat
        return currentDateTime.withYearOfCentury(soughtValue);
    }
    return currentDateTime;
}

From source file:ee.ut.soras.ajavtV2.mudel.ajavaljend.arvutus.SemLeidmiseAbimeetodid.java

License:Open Source License

/**
 *   Rakendab yldistatud Baldwini akent, et leida hetkele <tt>currentDateTime</tt> l2himat 
 *  ajahetke, mis vastab tingimustele <tt>field == soughtValue</tt>. Kui tingimustele vastav
 *  hetk j22b v2lja Baldwini akna raamidest, toimib kui tavaline SET operatsioon, omistades
 *  <tt>field := soughtValue</tt> ajahetke <tt>currentDateTime</tt> raames.
 *  <p>/*from w  w w. j  a v  a 2 s .  co  m*/
 *  NB! Praegu on implementeeritud ainult aastaaegade ja kvartalite lahendamine. 
    *  <p>
 *  <i>What's the Date? High Accuracy Interpretation of Weekday Name,</i> Dale, Mazur (2009)
 */
public static LocalDateTime applyBaldwinWindow(Granulaarsus field, LocalDateTime currentDateTime,
        String soughtValue) {
    // ---------------------------------
    //  SEASONs
    // ---------------------------------      
    if (field == Granulaarsus.MONTH && soughtValue != null && soughtValue.matches("(SP|SU|FA|WI)")) {
        LocalDate movingFocus = new LocalDate(currentDateTime);
        int addToCurrent = 0;
        // 1) Vaatame eelnevat 4-a kuud
        while (addToCurrent > -4) {
            String currentSeason = getSeason(movingFocus);
            if (currentSeason.equals(soughtValue)) {
                return currentDateTime.plusMonths(addToCurrent);
            }
            movingFocus = movingFocus.plusMonths(-1);
            addToCurrent--;
        }
        // 2) Vaatame jargnevat 4-a kuud
        movingFocus = new LocalDate(currentDateTime);
        addToCurrent = 0;
        while (addToCurrent < 4) {
            String currentSeason = getSeason(movingFocus);
            if (currentSeason.equals(soughtValue)) {
                return currentDateTime.plusMonths(addToCurrent);
            }
            movingFocus = movingFocus.plusMonths(1);
            addToCurrent++;
        }
        // Kui otsitav aastaaeg j2i aknast v2lja, k2sitleme seda kui "selle aasta" otsitud aastaaega
        return setMiddleOfSeason(currentDateTime, soughtValue);
    }
    // ---------------------------------
    //  QUARTER
    // ---------------------------------
    if (field == Granulaarsus.MONTH && soughtValue != null && soughtValue.matches("Q(1|2|3|4)")) {
        LocalDate movingFocus = new LocalDate(currentDateTime);
        int addToCurrent = 0;
        // 1) Vaatame eelnevat 4-a kuud
        while (addToCurrent > -4) {
            String currentSeason = getQuarterOfYear(movingFocus);
            if (currentSeason.equals(soughtValue)) {
                return currentDateTime.plusMonths(addToCurrent);
            }
            movingFocus = movingFocus.plusMonths(-1);
            addToCurrent--;
        }
        // 2) Vaatame jargnevat 4-a kuud
        movingFocus = new LocalDate(currentDateTime);
        addToCurrent = 0;
        while (addToCurrent < 4) {
            String currentSeason = getQuarterOfYear(movingFocus);
            if (currentSeason.equals(soughtValue)) {
                return currentDateTime.plusMonths(addToCurrent);
            }
            movingFocus = movingFocus.plusMonths(1);
            addToCurrent++;
        }
        // Kui otsitav kvartal j2i aknast v2lja, k2sitleme seda kui "selle aasta" otsitud kvartalit
        return setMiddleOfQuarterOfYear(currentDateTime, soughtValue);
    }
    return null;
}

From source file:ee.ut.soras.ajavtV2.mudel.ajavaljend.arvutus.TimeMLDateTimePoint.java

License:Open Source License

public void seekField(Granulaarsus field, int direction, String soughtValue, boolean excludingCurrent) {
    // ---------------------------------
    //  PART OF DAY
    // ---------------------------------
    if (field == Granulaarsus.TIME && soughtValue != null && soughtValue.matches("(NI|MO|AF|EV)")
            && direction != 0) {
        int dir = (direction > 0) ? (1) : (-1);
        // Loome k2esolevat ajafookust t2ielikult kirjeldava objekti
        LocalDateTime ajaFookus = getAsLocalDateTime();
        // AlgneMargend ehk p2evaosa, millest peame ennem m66da saama, kuni v6ime uue
        // v22rtuse omaks v6tta
        String algneMargend = (excludingCurrent)
                ? (SemLeidmiseAbimeetodid.getPartOfDay(ajaFookus.toLocalTime()))
                : (null);//from  w  w  w .j  a  v  a 2 s.  com
        if (!excludingCurrent) {
            // V6tame sammu tagasi, et esimene nihe tooks meid t2pselt k2esolevale tunnile   
            ajaFookus = ajaFookus.plusHours(dir * (-1));
        }
        int count = 0;
        while (true) {
            LocalDateTime uusFookus = ajaFookus.plusHours(1 * dir);
            ajaFookus = uusFookus;
            String newPartOfDay = SemLeidmiseAbimeetodid.getPartOfDay(uusFookus.toLocalTime());
            if (algneMargend != null) {
                if (algneMargend.equals(newPartOfDay)) {
                    continue;
                } else {
                    algneMargend = null;
                }
            }
            if (newPartOfDay != null && newPartOfDay.equals(soughtValue)) {
                algneMargend = newPartOfDay;
                count++;
                if (count == Math.abs(direction)) {
                    break;
                }
            }
        }
        this.partOfDay = soughtValue;
        updateTimeRepresentation(Granulaarsus.TIME, soughtValue, true, ADD_TYPE_OPERATION);
        this.underlyingTime = ajaFookus.toLocalTime();
        this.underlyingDate = ajaFookus.toLocalDate();
        functionOtherThanSetUsed = true;
    }
    // ---------------------------------
    //  WORKDAY OR WEEKEND
    // ---------------------------------
    if (field == Granulaarsus.DAY_OF_WEEK && soughtValue != null && soughtValue.matches("(WD|WE)")
            && direction != 0) {
        int dir = (direction > 0) ? (1) : (-1);
        LocalDate ajaFookus = new LocalDate(this.underlyingDate);
        // Algne p2ev ehk p2ev, millest tahame tingimata m66duda
        String algneMargend = (excludingCurrent) ? (SemLeidmiseAbimeetodid.getWordDayOrWeekend(ajaFookus))
                : (null);
        if (!excludingCurrent) {
            // V6tame sammu tagasi, et esimene nihe tooks meid t2pselt k2esolevale p2evale
            ajaFookus = ajaFookus.plusDays(dir * (-1));
        }
        int count = 0;
        while (true) {
            LocalDate nihutatudFookus = ajaFookus.plusDays(1 * dir);
            ajaFookus = nihutatudFookus;
            String toopaevVoiNadalalopp = SemLeidmiseAbimeetodid.getWordDayOrWeekend(ajaFookus);
            if (algneMargend != null) {
                if (algneMargend.equals(toopaevVoiNadalalopp)) {
                    continue;
                } else {
                    algneMargend = null;
                }
            }
            if (toopaevVoiNadalalopp.equals(soughtValue)) {
                algneMargend = toopaevVoiNadalalopp;
                count++;
                if (count == Math.abs(direction)) {
                    break;
                }
            }
        }
        this.underlyingDate = ajaFookus;
        (this.openedFields).put(VALUE_FIELD.DAY, soughtValue);
        updateDateRepresentation(Granulaarsus.DAY_OF_WEEK, soughtValue, true, ADD_TYPE_OPERATION);
        functionOtherThanSetUsed = true;
        this.dateModified = true;
    }
    // ---------------------------------
    //  SEASONs
    // ---------------------------------      
    if (field == Granulaarsus.MONTH && soughtValue != null && soughtValue.matches("(SP|SU|FA|WI)")
            && direction != 0) {
        int dir = (direction > 0) ? (1) : (-1);
        LocalDate ajaFookus = new LocalDate(this.underlyingDate);
        // Algne aastaaeg ehk aastaaeg, millest tahame tingimata m66duda
        String algneMargend = (excludingCurrent) ? (SemLeidmiseAbimeetodid.getSeason(ajaFookus)) : (null);
        if (!excludingCurrent) {
            // V6tame sammu tagasi, et esimene nihe tooks meid t2pselt k2esolevale kuule
            ajaFookus = ajaFookus.plusMonths(dir * (-1));
        }
        int count = 0;
        while (true) {
            LocalDate nihutatudFookus = ajaFookus.plusMonths(1 * dir);
            ajaFookus = nihutatudFookus;
            String aastaaeg = SemLeidmiseAbimeetodid.getSeason(ajaFookus);
            if (algneMargend != null) {
                if (algneMargend.equals(aastaaeg)) {
                    continue;
                } else {
                    algneMargend = null;
                }
            }
            if (aastaaeg.equals(soughtValue)) {
                algneMargend = aastaaeg;
                count++;
                if (count == Math.abs(direction)) {
                    break;
                }
            }
        }
        this.underlyingDate = ajaFookus;
        // Detsembri puhul liigume j2rgmisesse aastasse (st - talve loetakse aasta algusest) ...
        if ((this.underlyingDate).getMonthOfYear() == DateTimeConstants.DECEMBER) {
            this.underlyingDate = (this.underlyingDate).plusMonths(1);
        }
        openedFields.put(VALUE_FIELD.MONTH_OR_WEEK, soughtValue);
        updateDateRepresentation(Granulaarsus.MONTH, soughtValue, true, ADD_TYPE_OPERATION);
        functionOtherThanSetUsed = true;
        this.dateModified = true;
    }
    // ---------------------------------
    //  QUARTERs
    // ---------------------------------      
    if (field == Granulaarsus.MONTH && soughtValue != null && soughtValue.matches("Q(1|2|3|4)")
            && direction != 0) {
        int dir = (direction > 0) ? (1) : (-1);
        LocalDate ajaFookus = new LocalDate(this.underlyingDate);
        // Algne kvartal ehk kvartal, millest tahame tingimata m66duda
        String algneMargend = (excludingCurrent) ? (SemLeidmiseAbimeetodid.getQuarterOfYear(ajaFookus))
                : (null);
        if (!excludingCurrent) {
            // V6tame sammu tagasi, et esimene nihe tooks meid t2pselt k2esolevale kuule
            ajaFookus = ajaFookus.plusMonths(dir * (-1));
        }
        int count = 0;
        while (true) {
            LocalDate nihutatudFookus = ajaFookus.plusMonths(1 * dir);
            ajaFookus = nihutatudFookus;
            String kvartal = SemLeidmiseAbimeetodid.getQuarterOfYear(ajaFookus);
            if (algneMargend != null) {
                if (algneMargend.equals(kvartal)) {
                    continue;
                } else {
                    algneMargend = null;
                }
            }
            if (kvartal.equals(soughtValue)) {
                algneMargend = kvartal;
                count++;
                if (count == Math.abs(direction)) {
                    break;
                }
            }
        }
        this.underlyingDate = ajaFookus;
        String newQuarterVal = SemLeidmiseAbimeetodid.getQuarterOfYear(this.underlyingDate);
        openedFields.put(VALUE_FIELD.MONTH_OR_WEEK, newQuarterVal);
        updateDateRepresentation(Granulaarsus.MONTH, newQuarterVal, true, ADD_TYPE_OPERATION);
        functionOtherThanSetUsed = true;
        this.dateModified = true;
    }
}

From source file:org.gnucash.android.model.Recurrence.java

License:Apache License

/**
 * Sets the end time of this recurrence by specifying the number of occurences
 * @param numberOfOccurences Number of occurences from the start time
 *//*w  ww.  j a  v a2  s .  c  o m*/
public void setPeriodEnd(int numberOfOccurences) {
    LocalDateTime localDate = new LocalDateTime(mPeriodStart.getTime());
    LocalDateTime endDate;
    int occurrenceDuration = numberOfOccurences * mPeriodType.getMultiplier();
    switch (mPeriodType) {
    case DAY:
        endDate = localDate.plusDays(occurrenceDuration);
        break;
    case WEEK:
        endDate = localDate.plusWeeks(occurrenceDuration);
        break;
    default:
    case MONTH:
        endDate = localDate.plusMonths(occurrenceDuration);
        break;
    case YEAR:
        endDate = localDate.plusYears(occurrenceDuration);
        break;
    }
    mPeriodEnd = new Timestamp(endDate.toDateTime().getMillis());
}

From source file:org.gnucash.android.ui.chart.BarChartActivity.java

License:Apache License

/**
 * Returns a data object that represents a user data of the specified account types
 * @param accountType account's type which will be displayed
 * @return a {@code BarData} instance that represents a user data
 *//*from  w w w. ja  v a 2  s.  c  o m*/
private BarData getData(AccountType accountType) {
    List<BarEntry> values = new ArrayList<>();
    List<String> labels = new ArrayList<>();
    List<Integer> colors = new ArrayList<>();
    Map<String, Integer> accountToColorMap = new LinkedHashMap<>();
    List<String> xValues = new ArrayList<>();
    LocalDateTime tmpDate = new LocalDateTime(getStartDate(accountType).toDate().getTime());
    for (int i = 0; i <= Months.monthsBetween(getStartDate(accountType), getEndDate(accountType))
            .getMonths(); i++) {
        long start = tmpDate.dayOfMonth().withMinimumValue().millisOfDay().withMinimumValue().toDate()
                .getTime();
        long end = tmpDate.dayOfMonth().withMaximumValue().millisOfDay().withMaximumValue().toDate().getTime();
        List<Float> stack = new ArrayList<>();
        for (Account account : mAccountsDbAdapter.getSimpleAccountList()) {
            if (account.getAccountType() == accountType && !account.isPlaceholderAccount()
                    && account.getCurrency() == mCurrency) {

                double balance = mAccountsDbAdapter
                        .getAccountsBalance(Collections.singletonList(account.getUID()), start, end).asDouble();
                if (balance != 0) {
                    if (!accountToColorMap.containsKey(account.getUID())) {
                        Integer color;
                        if (mUseAccountColor) {
                            color = (account.getColorHexCode() != null)
                                    ? Color.parseColor(account.getColorHexCode())
                                    : COLORS[accountToColorMap.size() % COLORS.length];
                        } else {
                            color = COLORS[accountToColorMap.size() % COLORS.length];
                        }
                        accountToColorMap.put(account.getUID(), color);
                    }

                    stack.add((float) balance);
                    labels.add(account.getName());
                    colors.add(accountToColorMap.get(account.getUID()));
                    Log.d(TAG, accountType + tmpDate.toString(" MMMM yyyy ") + account.getName() + " = "
                            + stack.get(stack.size() - 1));
                }
            }
        }

        String stackLabels = labels.subList(labels.size() - stack.size(), labels.size()).toString();
        values.add(new BarEntry(floatListToArray(stack), i, stackLabels));

        xValues.add(tmpDate.toString(X_AXIS_PATTERN));

        tmpDate = tmpDate.plusMonths(1);
    }

    BarDataSet set = new BarDataSet(values, "");
    set.setStackLabels(labels.toArray(new String[labels.size()]));
    set.setColors(colors);

    if (set.getYValueSum() == 0) {
        mChartDataPresent = false;
        return getEmptyData();
    }
    mChartDataPresent = true;
    return new BarData(xValues, set);
}