Example usage for org.joda.time MutableDateTime addDays

List of usage examples for org.joda.time MutableDateTime addDays

Introduction

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

Prototype

public void addDays(final int days) 

Source Link

Document

Add a number of days to the date.

Usage

From source file:model.SqlInterface.java

/**
 * Using today's date and the date of the start of the week, determine how
 * much time has been spent on tasks so far this week.
 * /*from  www. ja  v a  2s .  c o  m*/
 * @param startDate The start date of the period.
 * @param endDate The end date of the period.
 * 
 * @return The total time spent on tasks this within the given period.
 */
public Period getWeekTally(DateTime startDate, DateTime endDate) {
    Period tally = new Period();
    // Need mutable to perform arithmetic
    MutableDateTime start = startDate.toMutableDateTime();
    // Need mutable to perform arithmetic
    MutableDateTime end = endDate.toMutableDateTime();
    // Only have 'isBefore' so add one day to make it equivalent to
    // 'isBeforeOrOnThisDay'
    end.addDays(1);

    ResultSet rs;

    while (start.isBefore(end)) {
        try {
            rs = statementHandler.executeQuery(
                    "select * from timelord where date = '" + Time.getReferableDate(start.toDateTime()) + "';");
            while (rs.next()) {
                // There should only be one for day and 7 for week
                tally = new Period(tally).plus(new Period(rs.getObject(4)));
            }

            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        start.addDays(1);
    }

    return tally;
}

From source file:model.SqlInterface.java

/**
 * Use this method to get all the values from the database corresponding to
 * the given JIRA project for the time period specified.
 * /*from ww  w . jav  a  2  s  .  co m*/
 * @param startDate The start date of the period to report on.
 * @param interval The length of time from the start date to report on.
 * @param jiraCode The Jira issue to report on.
 * 
 * @return ArrayList where each entry is an array containing the
 *         contents of each row from the database that was found: date,
 *         start, stop, delta, jira, description, dayTally.
 */
public Object[][] generateReport(DateTime startDate, Period interval, String jiraCode) {
    int taskCount = 0;
    String[][] tableData = null;

    MutableDateTime start = startDate.toMutableDateTime();
    // Need mutable to perform arithmetic
    MutableDateTime end = startDate.plus(interval).toMutableDateTime();
    // Only have 'isBefore' so add one day to make it equivalent to
    // 'isBeforeOrOnThisDay'
    end.addDays(1);

    ResultSet rs;
    try {
        rs = statementHandler.executeQuery("select * from timelord where date = '"
                + Time.getReferableDate(start.toDateTime()) + "' and jira = '" + jiraCode + "';");

        while (rs.next()) {
            taskCount++;
        }
        rs = statementHandler.executeQuery("select * from timelord where date = '"
                + Time.getReferableDate(start.toDateTime()) + "' and jira = '" + jiraCode + "';");

        tableData = new String[taskCount][6];

        taskCount = 0;
        while (start.isBefore(end)) {
            while (rs.next()) {
                tableData[taskCount][0] = Time.getFormattedDate(new DateTime(rs.getObject("start")));
                tableData[taskCount][1] = Time.getFormattedTime(new DateTime(rs.getObject("start")));
                tableData[taskCount][2] = Time.getFormattedTime(new DateTime(rs.getObject("stop")));
                tableData[taskCount][3] = Time.displayDelta(new Period(rs.getObject("delta")));
                tableData[taskCount][4] = rs.getString("jira");
                tableData[taskCount][5] = rs.getString("description");

                taskCount++;
            }
            start.addDays(1);
        }
    } catch (SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return tableData;
}

From source file:net.naonedbus.rest.controller.impl.HoraireController.java

License:Open Source License

/**
 * Rcuprer les horaires depuis le WebService.
 * //from w ww. j  av a2  s  .co m
 * @throws IOException
 * @throws MalformedURLException
 */
public synchronized List<Horaire> getAllFromWeb(final Arret arret, final DateMidnight date) throws IOException {
    final UrlBuilder url = new UrlBuilder(PATH);
    final List<HoraireNode> horaires;
    List<Horaire> result = null;

    url.addSegment(arret.getCodeArret());
    url.addSegment(arret.getCodeLigne());
    url.addSegment(arret.getCodeSens());
    url.addSegment(mDateFormat.format(date.toDate()));
    final HoraireContainer content = parseJsonObject(url.getUrl());

    MutableDateTime mutableDateTime = new MutableDateTime(date);

    if (content != null) {
        horaires = content.horaires;
        result = new ArrayList<Horaire>();

        int lastHour = Integer.MIN_VALUE;

        // Transformation des horaires TAN en horaire naonedbus.
        for (final HoraireNode horaireTan : horaires) {
            final int hour = Integer.parseInt(horaireTan.heure.replaceAll("[^\\d.]", ""));

            mutableDateTime.setHourOfDay(hour);

            // Changement de jour
            if (hour < lastHour) {
                mutableDateTime.addDays(1);
            }
            lastHour = hour;

            for (final String passage : horaireTan.passages) {
                int minute = Integer.parseInt(passage.replaceAll("[^\\d.]", ""));

                mutableDateTime.setMinuteOfHour(minute);

                final Horaire horaire = new Horaire();
                horaire.setJour(date);
                horaire.setHoraire(mutableDateTime.toDateTime());
                horaire.setTerminus(parseTerminus(passage, content.notes));
                horaire.setSection(new DateMidnight(horaire.getHoraire()));
                result.add(horaire);
            }
        }
    }

    return result;
}

From source file:nz.al4.airclock.MainActivity.java

License:Open Source License

@Override
public void onAlarmTimePicked(int hour, int minute) {

    DateTime currentTime = DateTime.now().toDateTime(mTimeCalculator.getTimeZone());
    Log.v("alarmCalc", "current time" + currentTime.toString());
    MutableDateTime desiredTime = currentTime.toMutableDateTime();
    desiredTime.setHourOfDay(hour);/*from  www  . j  a v  a 2s . c o m*/
    desiredTime.setMinuteOfHour(minute);

    // if after we set the hour + minute we get an earlier time, user probably means next day
    if (desiredTime.isBefore(currentTime)) {
        desiredTime.addDays(1);
    }

    DateTime alarmTime = mTimeCalculator.timeForAlarm(desiredTime.toDateTime().toLocalDateTime());

    DateTime originAlarm = alarmTime.toDateTime(mTimeCalculator.mOriginTime.getZone());
    DateTime destAlarm = alarmTime.toDateTime(mTimeCalculator.mDestTime.getZone());

    String msg = String.format("You should set your alarm for:\n%s (origin)\nor\n%s (destination)",
            dateTimeFormatter.print(originAlarm) + " " + originAlarm.getZone().toString(),
            dateTimeFormatter.print(destAlarm) + " " + destAlarm.getZone().toString());

    new AlertDialog.Builder(this).setTitle("Alarm").setMessage(msg).setCancelable(false)
            .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Whatever...
                }
            }).show();
}

From source file:org.codelibs.elasticsearch.common.joda.DateMathParser.java

License:Apache License

private long parseMath(String mathString, long time, boolean roundUp, DateTimeZone timeZone)
        throws ElasticsearchParseException {
    if (timeZone == null) {
        timeZone = DateTimeZone.UTC;/*from  w  w w  .j a  va 2  s .  c  o m*/
    }
    MutableDateTime dateTime = new MutableDateTime(time, timeZone);
    for (int i = 0; i < mathString.length();) {
        char c = mathString.charAt(i++);
        final boolean round;
        final int sign;
        if (c == '/') {
            round = true;
            sign = 1;
        } else {
            round = false;
            if (c == '+') {
                sign = 1;
            } else if (c == '-') {
                sign = -1;
            } else {
                throw new ElasticsearchParseException("operator not supported for date math [{}]", mathString);
            }
        }

        if (i >= mathString.length()) {
            throw new ElasticsearchParseException("truncated date math [{}]", mathString);
        }

        final int num;
        if (!Character.isDigit(mathString.charAt(i))) {
            num = 1;
        } else {
            int numFrom = i;
            while (i < mathString.length() && Character.isDigit(mathString.charAt(i))) {
                i++;
            }
            if (i >= mathString.length()) {
                throw new ElasticsearchParseException("truncated date math [{}]", mathString);
            }
            num = Integer.parseInt(mathString.substring(numFrom, i));
        }
        if (round) {
            if (num != 1) {
                throw new ElasticsearchParseException("rounding `/` can only be used on single unit types [{}]",
                        mathString);
            }
        }
        char unit = mathString.charAt(i++);
        MutableDateTime.Property propertyToRound = null;
        switch (unit) {
        case 'y':
            if (round) {
                propertyToRound = dateTime.yearOfCentury();
            } else {
                dateTime.addYears(sign * num);
            }
            break;
        case 'M':
            if (round) {
                propertyToRound = dateTime.monthOfYear();
            } else {
                dateTime.addMonths(sign * num);
            }
            break;
        case 'w':
            if (round) {
                propertyToRound = dateTime.weekOfWeekyear();
            } else {
                dateTime.addWeeks(sign * num);
            }
            break;
        case 'd':
            if (round) {
                propertyToRound = dateTime.dayOfMonth();
            } else {
                dateTime.addDays(sign * num);
            }
            break;
        case 'h':
        case 'H':
            if (round) {
                propertyToRound = dateTime.hourOfDay();
            } else {
                dateTime.addHours(sign * num);
            }
            break;
        case 'm':
            if (round) {
                propertyToRound = dateTime.minuteOfHour();
            } else {
                dateTime.addMinutes(sign * num);
            }
            break;
        case 's':
            if (round) {
                propertyToRound = dateTime.secondOfMinute();
            } else {
                dateTime.addSeconds(sign * num);
            }
            break;
        default:
            throw new ElasticsearchParseException("unit [{}] not supported for date math [{}]", unit,
                    mathString);
        }
        if (propertyToRound != null) {
            if (roundUp) {
                // we want to go up to the next whole value, even if we are already on a rounded value
                propertyToRound.add(1);
                propertyToRound.roundFloor();
                dateTime.addMillis(-1); // subtract 1 millisecond to get the largest inclusive value
            } else {
                propertyToRound.roundFloor();
            }
        }
    }
    return dateTime.getMillis();
}

From source file:org.elasticsearch.common.joda.DateMathParser.java

License:Apache License

private long parseMath(String mathString, long time, boolean roundUp) throws ElasticsearchParseException {
    MutableDateTime dateTime = new MutableDateTime(time, DateTimeZone.UTC);
    try {//from   w ww . j a v  a  2 s.  c  om
        for (int i = 0; i < mathString.length();) {
            char c = mathString.charAt(i++);
            int type;
            if (c == '/') {
                type = 0;
            } else if (c == '+') {
                type = 1;
            } else if (c == '-') {
                type = 2;
            } else {
                throw new ElasticsearchParseException(
                        "operator not supported for date math [" + mathString + "]");
            }

            int num;
            if (!Character.isDigit(mathString.charAt(i))) {
                num = 1;
            } else {
                int numFrom = i;
                while (Character.isDigit(mathString.charAt(i))) {
                    i++;
                }
                num = Integer.parseInt(mathString.substring(numFrom, i));
            }
            if (type == 0) {
                // rounding is only allowed on whole numbers
                if (num != 1) {
                    throw new ElasticsearchParseException(
                            "rounding `/` can only be used on single unit types [" + mathString + "]");
                }
            }
            char unit = mathString.charAt(i++);
            switch (unit) {
            case 'y':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.yearOfCentury().roundCeiling();
                    } else {
                        dateTime.yearOfCentury().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addYears(num);
                } else if (type == 2) {
                    dateTime.addYears(-num);
                }
                break;
            case 'M':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.monthOfYear().roundCeiling();
                    } else {
                        dateTime.monthOfYear().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addMonths(num);
                } else if (type == 2) {
                    dateTime.addMonths(-num);
                }
                break;
            case 'w':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.weekOfWeekyear().roundCeiling();
                    } else {
                        dateTime.weekOfWeekyear().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addWeeks(num);
                } else if (type == 2) {
                    dateTime.addWeeks(-num);
                }
                break;
            case 'd':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.dayOfMonth().roundCeiling();
                    } else {
                        dateTime.dayOfMonth().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addDays(num);
                } else if (type == 2) {
                    dateTime.addDays(-num);
                }
                break;
            case 'h':
            case 'H':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.hourOfDay().roundCeiling();
                    } else {
                        dateTime.hourOfDay().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addHours(num);
                } else if (type == 2) {
                    dateTime.addHours(-num);
                }
                break;
            case 'm':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.minuteOfHour().roundCeiling();
                    } else {
                        dateTime.minuteOfHour().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addMinutes(num);
                } else if (type == 2) {
                    dateTime.addMinutes(-num);
                }
                break;
            case 's':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.secondOfMinute().roundCeiling();
                    } else {
                        dateTime.secondOfMinute().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addSeconds(num);
                } else if (type == 2) {
                    dateTime.addSeconds(-num);
                }
                break;
            default:
                throw new ElasticsearchParseException(
                        "unit [" + unit + "] not supported for date math [" + mathString + "]");
            }
        }
    } catch (Exception e) {
        if (e instanceof ElasticsearchParseException) {
            throw (ElasticsearchParseException) e;
        }
        throw new ElasticsearchParseException("failed to parse date math [" + mathString + "]");
    }
    return dateTime.getMillis();
}

From source file:org.kuali.rice.kew.docsearch.service.impl.DocumentSearchServiceImpl.java

License:Educational Community License

protected DocumentSearchCriteria applyCriteriaDefaults(DocumentSearchCriteria criteria) {
    DocumentSearchCriteria.Builder comparisonCriteria = createEmptyComparisonCriteria(criteria);
    boolean isCriteriaEmpty = criteria.equals(comparisonCriteria.build());
    boolean isTitleOnly = false;
    boolean isDocTypeOnly = false;
    if (!isCriteriaEmpty) {
        comparisonCriteria.setTitle(criteria.getTitle());
        isTitleOnly = criteria.equals(comparisonCriteria.build());
    }/* w ww.jav a  2s . c  o  m*/

    if (!isCriteriaEmpty && !isTitleOnly) {
        comparisonCriteria = createEmptyComparisonCriteria(criteria);
        comparisonCriteria.setDocumentTypeName(criteria.getDocumentTypeName());
        isDocTypeOnly = criteria.equals(comparisonCriteria.build());
    }

    if (isCriteriaEmpty || isTitleOnly || isDocTypeOnly) {
        DocumentSearchCriteria.Builder criteriaBuilder = DocumentSearchCriteria.Builder.create(criteria);
        Integer defaultCreateDateDaysAgoValue = null;
        if (isCriteriaEmpty || isDocTypeOnly) {
            // if they haven't set any criteria, default the from created date to today minus days from constant variable
            defaultCreateDateDaysAgoValue = KewApiConstants.DOCUMENT_SEARCH_NO_CRITERIA_CREATE_DATE_DAYS_AGO;
        } else if (isTitleOnly) {
            // If the document title is the only field which was entered, we want to set the "from" date to be X
            // days ago.  This will allow for a more efficient query.
            defaultCreateDateDaysAgoValue = KewApiConstants.DOCUMENT_SEARCH_DOC_TITLE_CREATE_DATE_DAYS_AGO;
        }

        if (defaultCreateDateDaysAgoValue != null) {
            // add a default create date
            MutableDateTime mutableDateTime = new MutableDateTime();
            mutableDateTime.addDays(defaultCreateDateDaysAgoValue.intValue());
            criteriaBuilder.setDateCreatedFrom(mutableDateTime.toDateTime());
        }
        criteria = criteriaBuilder.build();
    }
    return criteria;
}

From source file:org.n52.sos.cache.AbstractCacheScheduler.java

License:Apache License

public MutableDateTime resolveNextScheduleDate(LocalTime localTime, DateTime referenceTime) {
    /*/*from  w ww.  j  ava 2s .co m*/
     * every 4am, starting with next
     */
    MutableDateTime mdt = referenceTime.toMutableDateTime();
    mdt.setHourOfDay(localTime.getHourOfDay());
    mdt.setMinuteOfHour(localTime.getMinuteOfHour());
    mdt.setSecondOfMinute(localTime.getSecondOfMinute());

    if (!referenceTime.isBefore(mdt)) {
        mdt.addDays(1);
    }

    Random random = new Random();
    mdt.addSeconds(random.nextInt(11) * 2);
    return mdt;
}

From source file:se.toxbee.sleepfighter.model.Alarm.java

License:Open Source License

/**
 * Returns when this alarm will ring.<br/>
 * If {@link #canHappen()} returns false, -1 will be returned.
 *
 * @param now the current time in unix epoch timestamp.
 * @return the time in unix epoch timestamp when alarm will next ring.
 *///from   w w w .  j a v a 2s.  co  m
public synchronized Long getNextMillis(long now) {
    if (!this.canHappen()) {
        return NEXT_NON_REAL;
    }

    MutableDateTime next = new MutableDateTime(now);
    next.setHourOfDay(this.hour);
    next.setMinuteOfHour(this.minute);
    next.setSecondOfMinute(this.second);

    // Check if alarm was earlier today. If so, move to next day
    if (next.isBefore(now)) {
        next.addDays(1);
    }
    // Offset for weekdays
    int offset = 0;

    // first weekday to check (0-6), getDayOfWeek returns (1-7)
    int weekday = next.getDayOfWeek() - 1;

    // Find the weekday the alarm should run, should at most run seven times
    for (int i = 0; i < 7; i++) {
        // Wrap to first weekday
        if (weekday > MAX_WEEK_INDEX) {
            weekday = 0;
        }
        if (this.enabledDays[weekday]) {
            // We've found the closest day the alarm is enabled for
            offset = i;
            break;
        }
        weekday++;
        offset++;
    }

    if (offset > 0) {
        next.addDays(offset);
    }

    return next.getMillis();
}

From source file:se.toxbee.sleepfighter.text.DateTextUtils.java

License:Open Source License

/**
 * Returns an array of strings with weekday names.
 *
 * @param indiceLength how long each string should be.
 * @param locale the desired locale.// w  ww.  j  a va  2s. c o m
 * @return the array of strings.
 */
public static final String[] getWeekdayNames(int indiceLength, Locale locale) {
    DateTimeFormatter fmt = DateTimeFormat.forPattern(Strings.repeat("E", indiceLength)).withLocale(locale);

    MutableDateTime time = new MutableDateTime();
    time.setDayOfWeek(DateTimeConstants.MONDAY);

    String[] names = new String[DateTimeConstants.DAYS_PER_WEEK];

    for (int day = 0; day < DateTimeConstants.DAYS_PER_WEEK; day++) {
        String name = fmt.print(time);

        if (name.length() > indiceLength) {
            name = name.substring(0, indiceLength);
        }

        names[day] = name;

        time.addDays(1);
    }

    return names;
}