Example usage for org.joda.time LocalDate LocalDate

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

Introduction

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

Prototype

public LocalDate(Object instant) 

Source Link

Document

Constructs an instance from an Object that represents a datetime.

Usage

From source file:com.sos.jobnet.creator.FrequencyChecker.java

License:Apache License

public void processJobNet(JobNetPlanDBItem bootstrapOrder) {

    String uuid = bootstrapOrder.getUuid();
    logger.info(msg.getMsg(JOBNETCH_I_0001, uuid)); // processing jobnet with id %1$s.
    logger.debug(msg.getMsg(JOBNETCH_D_0002, bootstrapOrder.getNodeId())); // bootstrap order has node id %2$s.

    Date d = bootstrapOrder.getPlannedStartTime();
    if (d == null) {
        String msgText = msg.getMsg(JOBNETCH_E_0001); // bootstrap order has no single_start
        logger.error(msgText);/*from   ww  w.  j a  v  a  2  s  . c o  m*/
        throw new JobNetException(msgText);
    }
    DateTime from = new DateTime(d);
    from = from.minusMillis(from.getMillisOfDay());
    DateTime to = from.plusDays(1);
    Interval baseInterval = new Interval(from, to);
    logger.debug(msg.getMsg(JOBNETCH_D_0001, fmtDateTime.print(from), fmtDateTime.print(to))); // searching for start times of job net nodes from %1$s to %2$s
    LocalDate forDay = new LocalDate(from);

    //      logger.debug(msg.getMsg(JOBNETCH_D_0003,fmtDate.print(baseInterval.getStart()))); // searching for starts at %2$s.
    List<JobNetPlanDBItem> jobnetOrders = getJobnet(uuid);
    if (jobnetOrders == null) {
        String msgText = msg.getMsg(JOBNETCH_E_0002, uuid);
        logger.error(msgText); // no jobnet found for UUID %1$s.
        throw new JobSchedulerException(msgText);
    }

    logger.debug(msg.getMsg(JOBNETCH_D_0004, jobnetOrders.size())); // the jobnet contains %1$s nodes.
    factory.setUseDefaultPeriod(true); // allows the use of runtime elements without or with incomplete periods

    planDbLayer.beginTransaction();
    for (JobNetPlanDBItem currentOrder : jobnetOrders) {
        JobNetNodeDBItem currentNode = getJobNetNode(currentOrder.getNodeId());
        if (!currentOrder.getBootstrap()) { // the properties for the bootstrap order has to be set in JobNetPlanCreator
            if (currentOrder.getIsRunnerSkipped()) {
                logger.info(msg.getMsg(JOBNETCH_I_0002, currentNode.getNode(), currentOrder.getNodeId())); // order %1$s (node id %2$s) is already skipped.
            } else {
                JSObjOrder jsOrder = getJSObjOrder(currentOrder.getOrderXml());
                JSObjRunTime runTime = jsOrder.getJSObjRunTime();
                if (runTime.hasSubsequentRunTimes()) {
                    LocalDate startDay = getNextStartDayInIntervalOrNull(runTime, baseInterval);
                    if (startDay == null) {
                        currentOrder.setIsRunnerSkipped(true);
                        // order %1$s (node id %2$s) has no start time for %3$s and will be skipped.
                        logger.info(msg.getMsg(JOBNETCH_I_0003, currentNode.getNode(), currentOrder.getNodeId(),
                                fmtDate.print(forDay)));
                    } else {
                        // order %1$s (node id %2$s) has a start time for %3$s and will NOT skipped.
                        logger.debug(msg.getMsg(JOBNETCH_I_0005, currentNode.getNode(),
                                currentOrder.getNodeId(), fmtDate.print(forDay)));
                        if (currentOrder.getIsRunnerOnDemand()) {
                            // order %1$s (node id %2$s) has to be started on demand.
                            logger.info(msg.getMsg(JOBNETCH_I_0006, currentNode.getNode(),
                                    currentOrder.getNodeId()));
                            currentOrder.setIsRunnerOnDemand(true);
                        }
                    }
                } else {
                    if (currentOrder.getIsRunnerOnDemand()) {
                        // order %1$s (node id %2$s) has no start time and will be NOT skipped.
                        currentOrder.setIsRunnerOnDemand(true);
                        logger.info(
                                msg.getMsg(JOBNETCH_I_0004, currentNode.getNode(), currentOrder.getNodeId()));
                    } else {
                        logger.debug(
                                "nothing to do - order has neither a start_time nor the parameter on_demand.");
                    }
                }
                logger.debug(currentOrder.getOrderXml().replace("\n", ""));
                planDbLayer.update(currentOrder);

            }
        }
        logRecord(currentNode, currentOrder);
    }
    planDbLayer.commit();
}

From source file:com.sos.jobnet.creator.FrequencyChecker.java

License:Apache License

/**
 * \brief get the next single start for an order
 * @return/* w  ww.j  ava 2s.  co  m*/
 */
private LocalDate getNextStartDayInIntervalOrNull(JSObjRunTime runTime, Interval forDay) {
    List<DateTime> startTimes = runTime.getDtSingleStarts(forDay);
    for (DateTime start : startTimes) {
        logger.debug(msg.getMsg(JOBNETCH_D_0008, fmtDateTime.print(start))); // start time: %1$s.
    }
    return (startTimes.size() == 0) ? null : new LocalDate(startTimes.get(0));
}

From source file:com.squid.kraken.v4.api.core.EngineUtils.java

License:Open Source License

/**
 * Convert the facet value into a date. 
 * If the value start with '=', it is expected to be a Expression, in which case we'll try to resolve it to a Date constant.
 * @param ctx// w  w  w  .j a va  2 s.  co  m
 * @param index
 * @param lower 
 * @param value
 * @param compareFromInterval 
 * @return
 * @throws ParseException
 * @throws ScopeException
 * @throws ComputingException 
 */
public Date convertToDate(Universe universe, DimensionIndex index, Bound bound, String value,
        IntervalleObject compareFromInterval) throws ParseException, ScopeException, ComputingException {
    if (value.equals("")) {
        return null;
    } else if (value.startsWith("__")) {
        //
        // support hard-coded shortcuts
        if (value.toUpperCase().startsWith("__COMPARE_TO_")) {
            // for compareTo
            if (compareFromInterval == null) {
                // invalid compare_to selection...
                return null;
            }
            if (value.equalsIgnoreCase("__COMPARE_TO_PREVIOUS_PERIOD")) {
                LocalDate localLower = new LocalDate(((Date) compareFromInterval.getLowerBound()).getTime());
                if (bound == Bound.UPPER) {
                    LocalDate date = localLower.minusDays(1);
                    return date.toDate();
                } else {
                    LocalDate localUpper = new LocalDate(
                            ((Date) compareFromInterval.getUpperBound()).getTime());
                    Days days = Days.daysBetween(localLower, localUpper);
                    LocalDate date = localLower.minusDays(1 + days.getDays());
                    return date.toDate();
                }
            }
            if (value.equalsIgnoreCase("__COMPARE_TO_PREVIOUS_MONTH")) {
                LocalDate localLower = new LocalDate(((Date) compareFromInterval.getLowerBound()).getTime());
                LocalDate compareLower = localLower.minusMonths(1);
                if (bound == Bound.LOWER) {
                    return compareLower.toDate();
                } else {
                    LocalDate localUpper = new LocalDate(
                            ((Date) compareFromInterval.getUpperBound()).getTime());
                    Days days = Days.daysBetween(localLower, localUpper);
                    LocalDate compareUpper = compareLower.plusDays(days.getDays());
                    return compareUpper.toDate();
                }
            }
            if (value.equalsIgnoreCase("__COMPARE_TO_PREVIOUS_YEAR")) {
                LocalDate localLower = new LocalDate(((Date) compareFromInterval.getLowerBound()).getTime());
                LocalDate compareLower = localLower.minusYears(1);
                if (bound == Bound.LOWER) {
                    return compareLower.toDate();
                } else {
                    LocalDate localUpper = new LocalDate(
                            ((Date) compareFromInterval.getUpperBound()).getTime());
                    Days days = Days.daysBetween(localLower, localUpper);
                    LocalDate compareUpper = compareLower.plusDays(days.getDays());
                    return compareUpper.toDate();
                }
            }
        } else {
            // for regular
            // get MIN, MAX first
            Intervalle range = null;
            if (index.getDimension().getType() == Type.CONTINUOUS) {
                if (index.getStatus() == Status.DONE) {
                    List<DimensionMember> members = index.getMembers();
                    if (!members.isEmpty()) {
                        DimensionMember member = members.get(0);
                        Object object = member.getID();
                        if (object instanceof Intervalle) {
                            range = (Intervalle) object;
                        }
                    }
                } else {
                    try {
                        DomainHierarchy hierarchy = universe
                                .getDomainHierarchy(index.getAxis().getParent().getDomain());
                        hierarchy.isDone(index, null);
                    } catch (ComputingException | InterruptedException | ExecutionException
                            | TimeoutException e) {
                        throw new ComputingException("failed to retrieve period interval");
                    }
                }
            }
            if (range == null) {
                range = IntervalleObject.createInterval(new Date(), new Date());
            }
            if (value.equalsIgnoreCase("__ALL")) {
                if (index.getDimension().getType() != Type.CONTINUOUS) {
                    return null;
                }
                if (bound == Bound.UPPER) {
                    return (Date) range.getUpperBound();
                } else {
                    return (Date) range.getLowerBound();
                }
            }
            if (value.equalsIgnoreCase("__LAST_DAY")) {
                if (bound == Bound.UPPER) {
                    return (Date) range.getUpperBound();
                } else {
                    return (Date) range.getUpperBound();
                }
            }
            if (value.equalsIgnoreCase("__LAST_7_DAYS")) {
                if (bound == Bound.UPPER) {
                    return (Date) range.getUpperBound();
                } else {
                    LocalDate localUpper = new LocalDate(((Date) range.getUpperBound()).getTime());
                    LocalDate date = localUpper.minusDays(6);// 6+1
                    return date.toDate();
                }
            }
            if (value.equalsIgnoreCase("__CURRENT_MONTH")) {
                if (bound == Bound.UPPER) {
                    return (Date) range.getUpperBound();
                } else {
                    LocalDate localUpper = new LocalDate(((Date) range.getUpperBound()).getTime());
                    LocalDate date = localUpper.withDayOfMonth(1);
                    return date.toDate();
                }
            }
            if (value.equalsIgnoreCase("__CURRENT_YEAR")) {
                if (bound == Bound.UPPER) {
                    return (Date) range.getUpperBound();
                } else {
                    LocalDate localUpper = new LocalDate(((Date) range.getUpperBound()).getTime());
                    LocalDate date = localUpper.withMonthOfYear(1).withDayOfMonth(1);
                    return date.toDate();
                }
            }
            if (value.equalsIgnoreCase("__PREVIOUS_MONTH")) {// the previous complete month
                if (bound == Bound.UPPER) {
                    LocalDate localUpper = new LocalDate(((Date) range.getUpperBound()).getTime());
                    LocalDate date = localUpper.withDayOfMonth(1).minusDays(1);
                    return date.toDate();
                } else {
                    LocalDate localUpper = new LocalDate(((Date) range.getUpperBound()).getTime());
                    LocalDate date = localUpper.withDayOfMonth(1).minusMonths(1);
                    return date.toDate();
                }
            }
            if (value.equalsIgnoreCase("__PREVIOUS_YEAR")) {// the previous complete month
                if (bound == Bound.UPPER) {
                    LocalDate localUpper = new LocalDate(((Date) range.getUpperBound()).getTime());
                    LocalDate date = localUpper.withMonthOfYear(1).withDayOfMonth(1).minusDays(1);
                    return date.toDate();
                } else {
                    LocalDate localUpper = new LocalDate(((Date) range.getUpperBound()).getTime());
                    LocalDate date = localUpper.withMonthOfYear(1).withDayOfMonth(1).minusYears(1);
                    return date.toDate();
                }
            }
        }
        throw new ScopeException("undefined facet expression alias: " + value);
    } else if (value.startsWith("=")) {
        // if the value starts by equal token, this is a formula that can be
        // evaluated
        try {
            String expr = value.substring(1);
            // check if the index content is available or wait for it
            DomainHierarchy hierarchy = universe.getDomainHierarchy(index.getAxis().getParent().getDomain(),
                    true);
            hierarchy.isDone(index, null);
            // evaluate the expression
            Object defaultValue = evaluateExpression(universe, index, expr, compareFromInterval);
            // check we can use it
            if (defaultValue == null) {
                //throw new ScopeException("unable to parse the facet expression as a constant: " + expr);
                // T1769: it's ok to return null
                return null;
            }
            if (!(defaultValue instanceof Date)) {
                throw new ScopeException("unable to parse the facet expression as a date: " + expr);
            }
            // ok, it's a date
            return (Date) defaultValue;
        } catch (ComputingException | InterruptedException | ExecutionException | TimeoutException e) {
            throw new ComputingException("failed to retrieve period interval");
        }
    } else {
        Date date = ServiceUtils.getInstance().toDate(value);
        if (bound == Bound.UPPER
                && !index.getAxis().getDefinitionSafe().getImageDomain().isInstanceOf(IDomain.TIME)) {
            // clear the timestamp
            return new LocalDate(date.getTime()).toDate();
        } else {
            return date;
        }
    }
}

From source file:com.squid.kraken.v4.core.analysis.datamatrix.CompareMerger.java

License:Open Source License

@Override
protected Object translateRightToLeft(Object right) {
    if (right instanceof Date && offset != null) {
        LocalDate delta = (new LocalDate(((Date) right).getTime())).plus(offset);
        return new java.sql.Date(delta.toDate().getTime());
    } else {//from w w w. j  a  v  a  2  s. c om
        return right;
    }
}

From source file:com.squid.kraken.v4.core.analysis.datamatrix.CompareMerger.java

License:Open Source License

@Override
protected Object translateLeftToRight(Object left) {
    if (left instanceof Date && offset != null) {
        LocalDate delta = (new LocalDate(((Date) left).getTime())).minus(offset);
        return new java.sql.Date(delta.toDate().getTime());
    } else {//from  w  ww.j a  v  a2  s  .co m
        return right;
    }
}

From source file:com.squid.kraken.v4.core.analysis.datamatrix.CompareMerger.java

License:Open Source License

@Override
protected int compareJoinValue(int pos, Object left, Object right) {
    if (right instanceof Date && offset != null) {
        return ((Date) left).compareTo((new LocalDate(((Date) right).getTime())).plus(offset).toDate());
    } else {/*  w  w w.j av a 2  s.  c o m*/
        return super.compareJoinValue(pos, left, right);
    }
}

From source file:com.squid.kraken.v4.core.analysis.engine.processor.AnalysisCompute.java

License:Open Source License

private IntervalleObject alignPastInterval(IntervalleObject presentInterval, IntervalleObject pastInterval,
        Axis joinAxis) throws ScopeException {

    if (joinAxis != null && presentInterval != null && pastInterval != null) {

        Object lowerPresent = presentInterval.getLowerBound();
        Object lowerPast = pastInterval.getLowerBound();
        Object upperPresent = presentInterval.getUpperBound();
        Object upperPast = pastInterval.getUpperBound();
        ////w  w  w .j  av  a2 s  . c om
        IDomain image = joinAxis.getDefinition().getImageDomain();
        if (lowerPresent instanceof Date && lowerPast instanceof Date) {

            DateTime lowerPastDT = new DateTime((Date) lowerPast);
            DateTime lowerPresentDT = new DateTime((Date) lowerPresent);
            DateTime upperPresentDT = new DateTime((Date) upperPresent);
            DateTime upperPastDT = new DateTime((Date) upperPast);

            // realign
            if (image.isInstanceOf(IDomain.YEARLY)) {
                // check if present is an exact number of years
                if (lowerPresentDT.getDayOfYear() == 1
                        && upperPresentDT.getDayOfYear() == upperPresentDT.dayOfYear().getMaximumValue()) {
                    // check of both periods have the same number of days
                    Period presentPeriod = new Period(new LocalDate(lowerPresent),
                            (new LocalDate(upperPresent)), PeriodType.days());
                    Period pastPeriod = new Period(new LocalDate(lowerPast), (new LocalDate(upperPast)),
                            PeriodType.days());
                    if (presentPeriod.getDays() == pastPeriod.getDays()) {
                        presentPeriod = new Period(new LocalDate(lowerPresent),
                                (new LocalDate(upperPresent)).plusDays(1), PeriodType.years());
                        pastPeriod = new Period(new LocalDate(lowerPast),
                                (new LocalDate(upperPast)).plusDays(1), PeriodType.years());

                        // realign
                        if (presentPeriod.getYears() > pastPeriod.getYears()) {
                            // some days are missing to align the periods
                            if (lowerPastDT.getDayOfYear() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(upperPastDT.getYear(), 1, 1, 0, 0).toDate();
                                return new IntervalleObject(newLowerPast, upperPast);
                            }
                            if (upperPastDT.getDayOfYear() != upperPastDT.dayOfYear().getMaximumValue()) {
                                // year over year
                                Date newUpperPast = new DateTime(upperPastDT.getYear(), 12, 31, 23, 59)
                                        .toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);
                            }
                        } else {
                            // either already aligned, or some days should
                            // be removed

                            if (upperPastDT.getDayOfYear() != upperPastDT.dayOfYear().getMaximumValue()) {
                                // year over Year
                                Date newUpperPast = new DateTime(upperPastDT.getYear() - 1, 12, 31, 23, 59)
                                        .toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);

                            }
                            if (lowerPastDT.getDayOfYear() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(lowerPastDT.getYear() + 1, 1, 1, 0, 0)
                                        .toDate();
                                return new IntervalleObject(newLowerPast, upperPast);
                            }

                        }
                    }
                }
            } else if (image.isInstanceOf(IDomain.QUATERLY) || image.isInstanceOf(IDomain.MONTHLY)) {
                // check if present is an exact number of month
                if (lowerPresentDT.getDayOfMonth() == 1
                        && upperPresentDT.getDayOfMonth() == upperPresentDT.dayOfMonth().getMaximumValue()) {
                    // check of both periods have the same number of days
                    Period presentPeriod = new Period(new LocalDate(lowerPresent), new LocalDate(upperPresent),
                            PeriodType.days());
                    Period pastPeriod = new Period(new LocalDate(lowerPast), new LocalDate(upperPast),
                            PeriodType.days());
                    if (presentPeriod.getDays() == pastPeriod.getDays()) {
                        // realign
                        presentPeriod = new Period(new LocalDate(lowerPresent),
                                (new LocalDate(upperPresent)).plusDays(1), PeriodType.months());
                        pastPeriod = new Period(new LocalDate(lowerPast),
                                (new LocalDate(upperPast)).plusDays(1), PeriodType.months());
                        if (presentPeriod.getMonths() > pastPeriod.getMonths()) {
                            // some days are missing

                            if (upperPastDT.getDayOfMonth() != upperPastDT.dayOfMonth().getMaximumValue()) {
                                // month over month
                                Date newUpperPast = new DateTime(upperPastDT.getYear(),
                                        upperPastDT.getMonthOfYear(),
                                        upperPastDT.dayOfMonth().getMaximumValue(), 23, 59).toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);
                            }

                            if (lowerPastDT.getDayOfMonth() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(lowerPastDT.getYear(),
                                        lowerPastDT.getMonthOfYear(), 1, 0, 0).toDate();
                                return new IntervalleObject(newLowerPast, upperPast);

                            }

                        } else {
                            // either already aligned, of some days should
                            // be removed
                            if (upperPastDT.getDayOfMonth() != upperPastDT.dayOfMonth().getMaximumValue()) {
                                /// month over month
                                if (upperPastDT.getMonthOfYear() == 1) {
                                    Date newUpperPast = new DateTime(upperPastDT.getYear() - 1, 12, 31, 23, 59)
                                            .toDate();
                                    return new IntervalleObject(lowerPast, newUpperPast);

                                } else {

                                    upperPastDT = upperPastDT.minusMonths(1);
                                    Date newUpperPast = new DateTime(upperPastDT.getYear(),
                                            upperPastDT.getMonthOfYear(),
                                            upperPastDT.dayOfMonth().getMaximumValue(), 23, 59).toDate();
                                    return new IntervalleObject(lowerPast, newUpperPast);
                                }
                            }
                            if (lowerPastDT.getDayOfMonth() != 1) {
                                // previous period
                                if (lowerPastDT.getMonthOfYear() == 12) {
                                    Date newLowerPast = new DateTime(lowerPastDT.getYear() + 1, 1, 1, 0, 0)
                                            .toDate();
                                    return new IntervalleObject(newLowerPast, upperPast);

                                } else {
                                    lowerPastDT = lowerPastDT.plusMonths(1);
                                    Date newLowerPast = new DateTime(lowerPastDT.getYear(),
                                            lowerPastDT.getMonthOfYear(), 1, 0, 0).toDate();
                                    return new IntervalleObject(newLowerPast, upperPast);

                                }

                            }

                        }
                    }
                }
            }
        }
    }
    return pastInterval;
}

From source file:com.squid.kraken.v4.core.analysis.engine.processor.AnalysisCompute.java

License:Open Source License

private Period computeOffset(IntervalleObject presentInterval, IntervalleObject pastInterval,
        AxisValues joinAxis) throws ScopeException {
    // it is better to compare on the lower bound because alignment on the
    // end of month is not accurate
    Object present = presentInterval.getLowerBound();
    Object past = pastInterval.getLowerBound();
    ///*w  w w .  j a v  a 2 s . co m*/

    IDomain image = joinAxis.getAxis().getDefinition().getImageDomain();
    PeriodType type = computePeriodType(image);
    //
    if (present instanceof Date && past instanceof Date) {

        Period presentPeriod = new Period(new LocalDate(((Date) presentInterval.getLowerBound()).getTime()),
                new LocalDate(((Date) presentInterval.getUpperBound()).getTime()).plusDays(1), type);

        Period pastPeriod = new Period(new LocalDate(((Date) pastInterval.getLowerBound()).getTime()),
                new LocalDate(((Date) pastInterval.getUpperBound()).getTime()).plusDays(1), type);

        Date pastDate = (Date) past;
        DateTime dt = new DateTime(pastDate);
        if (image.isInstanceOf(IDomain.YEARLY)) {
            if (presentPeriod.getYears() > pastPeriod.getYears()) {
                // e.g. presentPeriod of 365 days ->
                // presentPeriod.getYears=1 && past year of 366 days ->
                // pastPeriod.getYears=0
                DateTime newDT = new DateTime(dt.getYear(), 1, 1, 0, 0);
                pastDate = newDT.toDate();
            } else {
                if (dt.getDayOfYear() != 1) {
                    // e.g present period of 366 days -> past date at dec 31
                    DateTime newDT = new DateTime(dt.getYear() + 1, 1, 1, 0, 0);
                    pastDate = newDT.toDate();
                }
            }
        } else if (image.isInstanceOf(IDomain.QUATERLY) || image.isInstanceOf(IDomain.MONTHLY)) {

            if (presentPeriod.getMonths() > pastPeriod.getMonths()) {
                // e.g present period of 28 days(February) ->
                // pastPeriod.getMonths() = 0 (January has 31 days)
                DateTime newDT = new DateTime(dt.getYear(), dt.getMonthOfYear(), 1, 0, 0);
                pastDate = newDT.toDate();
            } else {
                if (dt.getDayOfMonth() != 1) {
                    // e.g. present period of 31 day(March) pastDate = Feb 6
                    if (dt.getMonthOfYear() == 12) {
                        DateTime newDT = new DateTime(dt.getYear() + 1, 1, 1, 0, 0);
                        pastDate = newDT.toDate();
                    } else {
                        DateTime newDT = new DateTime(dt.getYear(), dt.getMonthOfYear() + 1, 1, 0, 0);
                        pastDate = newDT.toDate();
                    }
                }
            }
        } else {
            // daily, keep Date as it is
        }
        return new Period(new LocalDate((pastDate).getTime()), new LocalDate(((Date) present).getTime()), type);

    } else {
        return null;
    }
}

From source file:com.stagecents.gl.api.service.CalendarCommandHandler.java

License:Open Source License

private LocalDate getYearStartDate(PeriodDTO[] periods) {
    LocalDate result = new LocalDate(Long.MAX_VALUE);
    for (int i = 0; i < periods.length; i++) {
        LocalDate startDate = periods[i].getStartDate();
        if (startDate.isBefore(result)) {
            result = startDate;/*from  w w w  .j  av  a 2 s  .  co m*/
        }
    }
    return result;
}

From source file:com.tasomaniac.muzei.tvshows.util.TimeTools.java

License:Apache License

/**
 * Calculates the current release date time. Adjusts for time zone effects on release time, e.g.
 * delays between time zones (e.g. in the United States) and DST. Adjusts for user-defined
 * offset.// w  w w  . j a va 2  s .  c  o m
 *
 * @param time See {@link #getShowReleaseTime(int)}.
 * @return The date is today or on the next day matching the given week day.
 */
public static Date getShowReleaseDateTime(@NonNull Context context, @NonNull LocalTime time, int weekDay,
        @Nullable String timeZone, @Nullable String country) {
    // determine show time zone (falls back to America/New_York)
    DateTimeZone showTimeZone = getDateTimeZone(timeZone);

    // create current date in show time zone, set local show release time
    LocalDateTime localDateTime = new LocalDate(showTimeZone).toLocalDateTime(time);

    // adjust day of week so datetime is today or within the next week
    // for daily shows (weekDay == 0) just use the current day
    if (weekDay >= 1 && weekDay <= 7) {
        // joda tries to preserve week
        // so if we want a week day earlier in the week, advance by 7 days first
        if (weekDay < localDateTime.getDayOfWeek()) {
            localDateTime = localDateTime.plusWeeks(1);
        }
        localDateTime = localDateTime.withDayOfWeek(weekDay);
    }

    localDateTime = handleHourPastMidnight(country, localDateTime);
    localDateTime = handleDstGap(showTimeZone, localDateTime);

    DateTime dateTime = localDateTime.toDateTime(showTimeZone);

    // handle time zone effects on release time for US shows (only if device is set to US zone)
    String localTimeZone = TimeZone.getDefault().getID();
    if (localTimeZone.startsWith(TIMEZONE_ID_PREFIX_AMERICA)) {
        dateTime = applyUnitedStatesCorrections(country, localTimeZone, dateTime);
    }

    return dateTime.toDate();
}