Example usage for org.joda.time LocalDateTime plusDays

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

Introduction

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

Prototype

public LocalDateTime plusDays(int days) 

Source Link

Document

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

Usage

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 ww .  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

/**
 *    Leiab <tt>currentDateTime</tt> granulaarsuse <tt>superField</tt> 
 *   <i>n</i>-inda alamosa, mis vastab tingimustele <tt>subField == soughtValueOfSubField</tt>.
 *   <p>/*from   ww  w.  ja v a 2 s  . c o  m*/
 *   Negatiivsete <i>n</i> vaartuste korral voetakse alamosa "tagantpoolt": vaartus 
 *   <i>n</i> == -1 tahistab <i>viimast</i>, <i>n</i> == -2 tahistab <i>eelviimast</i>
 *   jne alamosa.
 *   <p>
 *   Praegu on defineeritud ainult <i>kuu n-inda nadalapaeva leidmise</i> operatsioon (
 *   <tt>superField == MONTH</tt>, <tt>subField == DAY_OF_WEEK</tt>, <tt>soughtValueOfSubField == a weekdayname</tt> ).
 */
public static LocalDateTime findNthSubpartOfGranularity(Granulaarsus superField, Granulaarsus subField,
        int soughtValueOfSubField, int n, LocalDateTime currentDateTime) {
    if (superField == Granulaarsus.MONTH) {
        // --------------------------------------      
        //  Kuu n-inda nadalapaeva leidmine ...
        // --------------------------------------
        if (subField == Granulaarsus.DAY_OF_WEEK && DateTimeConstants.MONDAY <= soughtValueOfSubField
                && soughtValueOfSubField <= DateTimeConstants.SUNDAY) {
            if (n > 0) {
                //
                // Algoritm:  
                //    http://msdn.microsoft.com/en-us/library/aa227532(VS.60).aspx
                //
                // Kerime kaesoleva kuu esimese kuupaeva peale ...
                LocalDateTime newDate = currentDateTime.withDayOfMonth(1);
                // Leiame esimese otsitud nadalapaeva
                while (newDate.getDayOfWeek() != soughtValueOfSubField) {
                    newDate = newDate.plusDays(1);
                }
                int currentMonth = newDate.getMonthOfYear();
                newDate = newDate.plusDays((n - 1) * 7);
                if (currentMonth == newDate.getMonthOfYear()) {
                    // Kui kuu j2i kindlalt samaks, tagastame leitud nadalapaeva
                    return newDate;
                }
            } else if (n < 0) {
                // Negatiivsete vaartuste korral otsime lahendust lopust:
                // Kerime kuu viimase vaartuse peale
                LocalDateTime newDate = currentDateTime
                        .withDayOfMonth(currentDateTime.dayOfMonth().getMaximumValue());
                // Leiame viimase otsitud nadalapaeva
                while (newDate.getDayOfWeek() != soughtValueOfSubField) {
                    newDate = newDate.minusDays(1);
                }
                int currentMonth = newDate.getMonthOfYear();
                newDate = newDate.minusDays(((n * (-1)) - 1) * 7);
                if (currentMonth == newDate.getMonthOfYear()) {
                    // Kui kuu j2i kindlalt samaks, tagastame leitud nadalapaeva
                    return newDate;
                }
            }
        }
        // -------------------------------------------------
        //   Kuu n-inda ndala/ndalavahetuse leidmine ...
        // -------------------------------------------------
        // -------------------------------------------------------------------
        //   Teeme eelduse, et kuu esimene ndal on ndal, mis sisaldab kuu
        //  esimest nadalapaeva {soughtValueOfSubField};
        //   Ning analoogselt, kuu viimane ndal on ndal, mis sisaldab kuu 
        //  viimast nadalapaeva {soughtValueOfSubField};
        // -------------------------------------------------------------------
        if (subField == Granulaarsus.WEEK_OF_YEAR && DateTimeConstants.MONDAY <= soughtValueOfSubField
                && soughtValueOfSubField <= DateTimeConstants.SUNDAY) {
            if (n > 0) {
                // Kerime kaesoleva kuu esimese paeva peale ...
                LocalDateTime newDate = currentDateTime.withDayOfMonth(1);
                // Leiame kuu esimese neljapaeva/laupaeva
                while (newDate.getDayOfWeek() != soughtValueOfSubField) {
                    newDate = newDate.plusDays(1);
                }
                newDate = newDate.plusDays((n - 1) * 7);
                return newDate;
            } else if (n < 0) {
                // Negatiivsete vaartuste korral otsime lahendust lopust:
                // Kerime kuu viimase vaartuse peale
                LocalDateTime newDate = currentDateTime
                        .withDayOfMonth(currentDateTime.dayOfMonth().getMaximumValue());
                // Leiame viimase neljapaeva/laupaeva
                while (newDate.getDayOfWeek() != soughtValueOfSubField) {
                    newDate = newDate.minusDays(1);
                }
                newDate = newDate.minusDays(((n * (-1)) - 1) * 7);
                return newDate;
            }
        }
    }
    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  ww  w .j  a v  a 2s .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:energy.usef.agr.workflow.altstep.AgrFlexOfferDetermineFlexibilityStubOffer.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from ww w .  ja va  2s  .  com
public WorkflowContext invoke(WorkflowContext context) {
    LOGGER.debug("Received context parameters: {}", context);

    LocalDate period = context.get(FlexOfferDetermineFlexibilityStepParameter.IN.PERIOD.name(),
            LocalDate.class);
    Integer ptuDuration = context.get(FlexOfferDetermineFlexibilityStepParameter.IN.PTU_DURATION.name(),
            Integer.class);
    List<FlexRequestDto> inputFlexRequests = context
            .get(FlexOfferDetermineFlexibilityStepParameter.IN.FLEX_REQUEST_DTO_LIST.name(), List.class);
    List<FlexOfferDto> existingFlexOffers = context
            .get(FlexOfferDetermineFlexibilityStepParameter.IN.FLEX_OFFER_DTO_LIST.name(), List.class);
    // build maps of:  ConnectionGroup > List<ConnectionDto>
    Map<String, List<ConnectionPortfolioDto>> connectionPortfolioDtoMap = buildConnectionDtoPerConnectionGroup(
            context);

    // retrieve map of flexible potential per congestion point
    Map<String, Map<Integer, Map<ConsumptionProductionTypeDto, BigInteger>>> potentialFlexPerConnectionGroupPerPtu = fetchPotentialFlex(
            connectionPortfolioDtoMap, period, ptuDuration);
    Map<String, Map<Integer, Map<ConsumptionProductionTypeDto, BigInteger>>> offeredFlexPerConnectionGroupPerPtu = fetchAlreadyOfferedFlex(
            existingFlexOffers);

    LocalDateTime now = DateTimeUtil.getCurrentDateTime();

    // retrieve APX prices from the pbc feeder
    final int ptusPerDay = Days.ONE.toStandardMinutes().getMinutes()
            / context.get(FlexOfferDetermineFlexibilityStepParameter.IN.PTU_DURATION.name(), Integer.class);
    Map<Integer, BigDecimal> apxPrices = pbcFeederService.retrieveApxPrices(period, 1, ptusPerDay);
    List<FlexOfferDto> outputFlexOffers = new ArrayList<>();
    for (FlexRequestDto flexRequestDto : inputFlexRequests) {
        boolean congestionPointContext = isFlexRequestForCongestionPoint(flexRequestDto);
        String connectionGroup = flexRequestDto.getConnectionGroupEntityAddress();
        // possibleFlex = potentialFlex - offered_flex
        Map<Integer, Map<ConsumptionProductionTypeDto, BigInteger>> possibleFlexPerPtu = fetchPossibleFlex(
                potentialFlexPerConnectionGroupPerPtu.get(connectionGroup),
                offeredFlexPerConnectionGroupPerPtu.getOrDefault(connectionGroup, new HashMap<>()));
        // create new flex offer
        FlexOfferDto flexOfferDto = new FlexOfferDto();
        flexOfferDto.setFlexRequestSequenceNumber(flexRequestDto.getSequenceNumber());
        flexOfferDto.setPeriod(flexRequestDto.getPeriod());
        flexOfferDto.setConnectionGroupEntityAddress(flexRequestDto.getConnectionGroupEntityAddress());
        flexOfferDto.setParticipantDomain(flexRequestDto.getParticipantDomain());
        flexOfferDto.setExpirationDateTime(now.plusDays(FLEX_OFFER_EXPIRATION_DAYS).withTime(0, 0, 0, 0));

        // for each ptu of the flex request
        for (PtuFlexRequestDto ptu : flexRequestDto.getPtus()) {
            BigInteger maxPotentialFlex;
            BigDecimal price;
            if (ptu.getDisposition() == DispositionTypeDto.AVAILABLE) {
                maxPotentialFlex = ZERO;
                price = BigDecimal.ZERO;
            } else {
                maxPotentialFlex = determineMaxPotentialFlex(possibleFlexPerPtu, ptu);
                price = determinePrice(possibleFlexPerPtu, apxPrices, ptu, congestionPointContext, ptuDuration);
            }

            PtuFlexOfferDto ptuFlexOfferDto = new PtuFlexOfferDto();
            ptuFlexOfferDto.setPower(maxPotentialFlex);
            ptuFlexOfferDto.setPrice(price.setScale(PRECISION_OF_PRICE, RoundingMode.HALF_UP));
            ptuFlexOfferDto.setPtuIndex(ptu.getPtuIndex());
            LOGGER.trace("{} added to {}.", ptuFlexOfferDto, flexOfferDto);
            flexOfferDto.getPtus().add(ptuFlexOfferDto);
        }
        outputFlexOffers.add(flexOfferDto);
    }
    context.setValue(FlexOfferDetermineFlexibilityStepParameter.OUT.FLEX_OFFER_DTO_LIST.name(),
            outputFlexOffers);
    return context;
}

From source file:energy.usef.core.util.DateTimeUtil.java

License:Apache License

/**
 * Gets the number of milliseconds until the next occurence of the local time (which is the current day or the day after).
 *
 * @param localTime {@link LocalTime}/*from  www .j  a  va 2  s. c o  m*/
 * @return the number of milliseconds.
 */
public static Long millisecondDelayUntilNextTime(LocalTime localTime) {
    LocalDateTime schedule = getCurrentDateWithTime(localTime);
    if (schedule.isBefore(getCurrentDateTime())) {
        schedule = schedule.plusDays(1);
    }
    return new Duration(getCurrentDateTime().toDateTime(), schedule.toDateTime()).getMillis();
}

From source file:org.apache.isis.viewer.wicket.ui.components.scalars.jodatime.DateConverterForJodaLocalDateTime.java

License:Apache License

@Override
protected String doConvertToString(LocalDateTime value, Locale locale) {
    return value.plusDays(adjustBy).toString(getFormatterForDateTimePattern());
}

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
 *//*from   w  w w  .  jav  a  2  s.c om*/
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.jtwig.functions.builtin.DateFunctions.java

License:Apache License

private Date modify(String modifyString, LocalDateTime localDateTime) throws FunctionException {

    LocalDateTime result;//from  w w  w  . jav  a2  s  .c  o m

    Matcher matcher = compile(MODIFY_PATTERN).matcher(modifyString);
    matcher.find();

    int signal = 1;

    if (matcher.group(1).equals("-"))
        signal = -1;

    int val = Integer.valueOf(matcher.group(2)) * signal;
    String type = matcher.group(3).toLowerCase();

    if (type.startsWith("day"))
        result = localDateTime.plusDays(val);
    else if (type.startsWith("month"))
        result = localDateTime.plusMonths(val);
    else if (type.startsWith("year"))
        result = localDateTime.plusYears(val);
    else if (type.startsWith("second"))
        result = localDateTime.plusSeconds(val);
    else if (type.startsWith("hour"))
        result = localDateTime.plusHours(val);
    else if (type.startsWith("minute"))
        result = localDateTime.plusMinutes(val);
    else
        throw new FunctionException("Unknown type " + matcher.group(3));

    return result.toDate();
}

From source file:org.kuali.kpme.tklm.time.timesummary.service.TimeSummaryServiceImpl.java

License:Educational Community License

/**
 * Handles the generation of the display header for the time summary.
 *
 * @param cal The PayCalendarEntries object we are using to derive information.
 * @param dayArrangements Container passed in to store the position of week / period aggregate sums
 *
 * @return An in-order string of days for this period that properly accounts
 * for FLSA week boundaries in the pay period.
 *//*w ww. java2  s  . c o  m*/
@Override
public List<String> getHeaderForSummary(CalendarEntry cal, List<Boolean> dayArrangements) {
    List<String> header = new ArrayList<String>();
    if (cal == null) {
        return Collections.emptyList();
    }
    // Maps directly to joda time day of week constants.
    int flsaBeginDay = this.getPayCalendarForEntry(cal).getFlsaBeginDayConstant();
    boolean virtualDays = false;
    LocalDateTime startDate = cal.getBeginPeriodLocalDateTime();
    LocalDateTime endDate = cal.getEndPeriodLocalDateTime();

    // Increment end date if we are on a virtual day calendar, so that the
    // for loop can account for having the proper amount of days on the
    // summary calendar.
    if (endDate.get(DateTimeFieldType.hourOfDay()) != 0 || endDate.get(DateTimeFieldType.minuteOfHour()) != 0
            || endDate.get(DateTimeFieldType.secondOfMinute()) != 0) {
        endDate = endDate.plusDays(1);
        virtualDays = true;
    }

    boolean afterFirstDay = false;
    int week = 1;
    for (LocalDateTime currentDate = startDate; currentDate.compareTo(endDate) < 0; currentDate = currentDate
            .plusDays(1)) {

        if (currentDate.getDayOfWeek() == flsaBeginDay && afterFirstDay) {
            header.add("Week " + week);
            dayArrangements.add(false);
            week++;
        }

        header.add(makeHeaderDiplayString(currentDate, virtualDays));
        dayArrangements.add(true);

        afterFirstDay = true;
    }

    // We may have a very small final "week" on this pay period. For now
    // we will mark it as a week, and if someone doesn't like it, it can
    // be removed.
    if (!header.isEmpty() && !header.get(header.size() - 1).startsWith("Week")) {
        dayArrangements.add(false);
        header.add("Week " + week);
    }

    header.add("Period Total");
    dayArrangements.add(false);
    return header;
}

From source file:org.kuali.kpme.tklm.time.timesummary.service.TimeSummaryServiceImpl.java

License:Educational Community License

/**
 * Helper function to generate display text for the summary header.
 * @param currentDate The date we are generating for.
 * @param virtualDays Whether or not virtual days apply.
 * @return A string appropriate for UI display.
 *//*from   w ww  .  j a  v a  2  s .  com*/
private String makeHeaderDiplayString(LocalDateTime currentDate, boolean virtualDays) {
    StringBuilder display = new StringBuilder();

    display.append(currentDate.toString("E"));
    if (virtualDays) {
        LocalDateTime nextDate = currentDate.plusDays(1);
        display.append(" - ");
        display.append(nextDate.toString("E"));
    }

    display.append("<br />");

    display.append(currentDate.toString(TkConstants.DT_ABBREV_DATE_FORMAT));
    if (virtualDays) {
        LocalDateTime nextDate = currentDate.plusDays(1);
        display.append(" - ");
        display.append(nextDate.toString(TkConstants.DT_ABBREV_DATE_FORMAT));
    }

    return display.toString();
}