Example usage for java.util Calendar DAY_OF_YEAR

List of usage examples for java.util Calendar DAY_OF_YEAR

Introduction

In this page you can find the example usage for java.util Calendar DAY_OF_YEAR.

Prototype

int DAY_OF_YEAR

To view the source code for java.util Calendar DAY_OF_YEAR.

Click Source Link

Document

Field number for get and set indicating the day number within the current year.

Usage

From source file:com.feilong.core.date.DateUtil.java

/**
 * ? <code>date</code>().//from  www.ja v  a 2  s .  c  o m
 * 
 * <pre class="code">
 * DateUtil.getDayOfYear(<code>2013-01-01</code>)    =1
 * DateUtil.getDayOfYear(<code>2013-01-05</code>)    =5
 * </pre>
 * 
 * @param date
 *            ?
 * @return  <code>date</code> null, {@link NullPointerException}<br>
 * @since 1.0.2
 */
public static int getDayOfYear(Date date) {
    return CalendarUtil.getFieldValue(date, Calendar.DAY_OF_YEAR);
}

From source file:de.blizzy.backup.backup.BackupRun.java

private void removeOldBackupsDaily() {
    // collect IDs of all but the most recent backup each day
    Set<Integer> backupsToRemove = new HashSet<>();
    List<Date> days = getBackupRunsDays(BackupPlugin.KEEP_HOURLIES_DAYS);
    Calendar c = Calendar.getInstance();
    for (Date day : days) {
        long start = day.getTime();
        c.setTimeInMillis(start);/*from   w  w  w.  ja  v a  2  s  . c o  m*/
        c.add(Calendar.DAY_OF_YEAR, 1);
        long end = c.getTimeInMillis();
        List<Integer> ids = getBackupIds(start, end);
        if (ids.size() >= 2) {
            ids.remove(0);
            backupsToRemove.addAll(ids);
        }
    }

    BackupPlugin.getDefault().logMessage("removing backups (daily): " + backupsToRemove); //$NON-NLS-1$
    if (!backupsToRemove.isEmpty()) {
        removeBackups(backupsToRemove);
    }
}

From source file:jef.tools.DateUtils.java

/**
 * /*from w  w  w .java 2s  .c o  m*/
 *  ?? ?DateDate
 * 
 * @param date
 *            
 * @param year
 *            ?
 * @param month
 *            ?
 * @param day
 *            ?
 * @return ?
 */
public static Date adjustDate(Date date, int year, int month, int day) {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.add(Calendar.YEAR, year);
    c.add(Calendar.MONTH, month);
    c.add(Calendar.DAY_OF_YEAR, day);
    return c.getTime();
}

From source file:com.aurel.track.move.ItemMoveBL.java

public static Date stepForward(Date dateParam, int steps, boolean withCheckingFreeDays) {
    if (dateParam == null) {
        return null;
    }/*from w  w w . j a  v a2s .c  o  m*/
    int actualSteps = 0;
    Calendar cal = Calendar.getInstance();
    cal.setTime(dateParam);
    Date newDate = new Date();
    while (actualSteps < steps) {
        cal.add(Calendar.DAY_OF_YEAR, 1);
        newDate = cal.getTime();
        if (withCheckingFreeDays) {
            if (!WorkDaysConfigImplementation.isSaturday(newDate)
                    && !WorkDaysConfigImplementation.isSunday(newDate)
                    && !WorkDaysConfigImplementation.isFreeDay(newDate)) {
                actualSteps++;
            }
        } else {
            actualSteps++;
        }
    }
    return newDate;
}

From source file:com.panet.imeta.core.row.ValueDataUtil.java

public static Object addDays(ValueMetaInterface metaA, Object dataA, ValueMetaInterface metaB, Object dataB)
        throws KettleValueException {
    if (metaA.isDate() && metaB.isInteger()) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(metaA.getDate(dataA));
        cal.add(Calendar.DAY_OF_YEAR, metaB.getInteger(dataB).intValue());

        return cal.getTime();
    }//from  w ww  . j a v a 2  s  .  c  o  m

    throw new KettleValueException("The 'addDays' function only works with a date and an integer");
}

From source file:com.alkacon.opencms.calendar.CmsCalendarDisplay.java

/**
 * Returns all displayed days of the specified week with their corresponding entries as lists.<p>
 * /*from   w  ww . ja  v a2  s .  c om*/
 * The key of the Map has to be a Date object.<p>
 * 
 * The Map values are always lists of {@link CmsCalendarEntry} objects, if no entries are available for a specific day,
 * an empty List is returned.<p>
 * 
 * @param year the year of the month to display
 * @param week the week of the year to display
 * @return all displayed days of the specified day range with their corresponding entries as lists
 */
public Map getEntriesForWeek(int year, int week) {

    Calendar startDay = new GregorianCalendar(getJsp().getRequestContext().getLocale());
    startDay.set(Calendar.YEAR, year);
    startDay.set(Calendar.WEEK_OF_YEAR, week);
    startDay.set(Calendar.DAY_OF_WEEK, startDay.getFirstDayOfWeek());

    Calendar endDay = (Calendar) startDay.clone();
    endDay.add(Calendar.DAY_OF_YEAR, 6);

    return getEntriesForDays(startDay, endDay);
}

From source file:de.blizzy.backup.backup.BackupRun.java

private void removeOldBackupsWeekly() {
    // collect IDs of all but the most recent backup each week
    Set<Integer> backupsToRemove = new HashSet<>();
    List<Date> days = getBackupRunsDays(BackupPlugin.KEEP_DAILIES_DAYS);
    Calendar c = Calendar.getInstance();
    for (Date day : days) {
        long start = getWeekStart(day).getTime();
        c.setTimeInMillis(start);//from   ww  w .  java2 s  . c  o m
        c.add(Calendar.DAY_OF_YEAR, 7);
        long end = c.getTimeInMillis();
        List<Integer> ids = getBackupIds(start, end);
        if (ids.size() >= 2) {
            ids.remove(0);
            backupsToRemove.addAll(ids);
        }
    }

    BackupPlugin.getDefault().logMessage("removing backups (weekly): " + backupsToRemove); //$NON-NLS-1$
    if (!backupsToRemove.isEmpty()) {
        removeBackups(backupsToRemove);
    }
}

From source file:de.blizzy.backup.backup.BackupRun.java

private Date getWeekStart(Date date) {
    int firstWeekday = Calendar.getInstance().getFirstDayOfWeek();
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(date.getTime());//from w w w.ja v a2  s .  c  o m
    for (;;) {
        int weekday = c.get(Calendar.DAY_OF_WEEK);
        if (weekday == firstWeekday) {
            break;
        }
        c.add(Calendar.DAY_OF_YEAR, -1);
    }
    return new Date(c.getTimeInMillis());
}

From source file:com.aurel.track.move.ItemMoveBL.java

public static Integer getNumberOfSundaysFromInterval(Date startDateParam, Date endDateParam) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDateParam);//  w ww  . j av  a  2  s  .co  m
    int numOfSunday = 0;
    while (DateTimeUtils.less(calendar.getTime(), endDateParam)) {
        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            numOfSunday++;
        }
        calendar.add(Calendar.DAY_OF_YEAR, 1);
    }
    return numOfSunday;
}

From source file:com.zimbra.cs.mailbox.calendar.ZRecur.java

public List<Date> expandRecurrenceOverRange(ParsedDateTime dtStart, long rangeStart, long rangeEnd)
        throws ServiceException {
    List<Date> toRet = new LinkedList<Date>();

    Date rangeStartDate = new Date(rangeStart);
    // subtract 1000ms (1sec) because the code in the method treats
    // end time as inclusive while the rangeEnd input argument is
    // exclusive value
    Date rangeEndDate = new Date(rangeEnd - 1000);
    Date dtStartDate = new Date(dtStart.getUtcTime());

    Date earliestDate;//from   w w w.  j  av  a2s.com
    if (dtStartDate.after(rangeStartDate))
        earliestDate = dtStartDate;
    else
        earliestDate = rangeStartDate;

    if (mUntil != null) {
        Date until = mUntil.getDateForRecurUntil(dtStart.getTimeZone());
        if (until.before(rangeEndDate))
            rangeEndDate = until;
    }

    // Set limit of expansion count.
    int maxInstancesFromConfig = sExpansionLimits.maxInstances;
    int maxInstancesExpanded;
    if (maxInstancesFromConfig <= 0)
        maxInstancesExpanded = mCount;
    else if (mCount <= 0)
        maxInstancesExpanded = maxInstancesFromConfig;
    else
        maxInstancesExpanded = Math.min(mCount, maxInstancesFromConfig);
    int numInstancesExpanded = 1; // initially 1 rather than 0 because DTSTART is always included

    // Set hard limit of expansion time range.  (bug 21989)
    ParsedDateTime earliestDateTime = ParsedDateTime.fromUTCTime(earliestDate.getTime());
    Date hardEndDate = getEstimatedEndTime(earliestDateTime);
    if (hardEndDate.before(rangeEndDate))
        rangeEndDate = hardEndDate;

    if (rangeEndDate.before(earliestDate)) {
        ZimbraLog.calendar.debug(
                "Expanding recurrence over range where range end %s is before earliest date %s",
                DateUtil.formatDate(rangeEndDate), DateUtil.formatDate(earliestDate));
        return toRet;
    }

    GregorianCalendar cur = dtStart.getCalendarCopy();
    int baseMonthDay = cur.get(Calendar.DAY_OF_MONTH);
    boolean baseIsLeapDay = ((baseMonthDay == 29) && (cur.get(Calendar.MONTH) == Calendar.FEBRUARY));

    // until we hit rangeEnd, or we've SAVED count entries:
    //
    //     gather each set {
    //
    //
    //
    //        curDate forward one INTERVAL
    //
    //     }
    //     check Set against BYSETPOS & ranges & count
    //

    int interval = mInterval;
    if (interval <= 0)
        interval = 1;

    // DTSTART is always part of the expansion, as long as it falls within
    // the range.
    if (!dtStartDate.before(earliestDate) && !dtStartDate.after(rangeEndDate))
        toRet.add(dtStartDate);

    int numConsecutiveIterationsWithoutMatchingInstance = 0;
    boolean pastHardEndTime = false;
    long numIterations = 0; // track how many times we looped
    while (!pastHardEndTime && (maxInstancesExpanded <= 0 || numInstancesExpanded < maxInstancesExpanded)) {
        numIterations++;
        boolean curIsAtOrAfterEarliestDate = !cur.getTime().before(earliestDate);
        boolean curIsAfterEndDate = cur.getTime().after(rangeEndDate);
        List<Calendar> addList = new LinkedList<Calendar>();

        switch (mFreq) {
        case HOURLY:
            /*
             * BYSECOND - for each listed second
             * BYMINUTE - for each listed minute in hour
             * BYHOUR - match iff in hour list
             * BYDAY - for each day listed
             * BYMONTHDAY - only those monthdays
             * BYYEARDAY - only those yeardays
             * BYMONTH - only those months
             */
            if (!checkMonthList(cur))
                continue;

            if (!checkYearDayList(cur))
                continue;

            if (!checkMonthDayList(cur))
                continue;

            if (!checkDayList(cur))
                continue;

            if (!checkHourList(cur))
                continue;

            addList.add((Calendar) (cur.clone()));

            cur.add(Calendar.HOUR_OF_DAY, interval);

            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);

            break;
        case DAILY:
            /*
             * BYSECOND - for each listed second in day
             * BYMINUTE - for each listed minute in day
             * BYHOUR - for each listed hour in day
             * BYDAY - no ordinal allowed, match iff in day list
             * BYMONTHDAY - only that day
             * BYYEARDAY - only that day
             * BYWEEKNO -- YEARLY ONLY
             * BYMONTH - only that month
             *
             * while (count check & until check & rangeEnd check) {
             *    if (byMonth && !month matches)
             *      curDay = set MONTH to matching month
             *
             *    if (byYearDay && !yearday matches)
             *      curDay = set DAY to next matching yearday
             *
             *    if (byMonthday && !monthday matches)
             *      curDay = skip to next matching monthday
             *
             *    if (byDay && !day in list)
             *      curDay = skip to next mathcing byDay
             *
             *    if (!byHour or FOR EACH HOUR IN HOURLIST)
             *      if (!byMinute or FOR EACH MINUTE IN MINLIST)
             *        if (!bySecond or FOR EACH SECOND IN LIST)
             *          ----add to list---
             *
             *     check against BYSETPOS
             *
             *     curDay+=1 day
             * }
             *
             */

            if (!checkMonthList(cur))
                continue;

            if (!checkYearDayList(cur))
                continue;

            if (!checkMonthDayList(cur))
                continue;

            if (!checkDayList(cur))
                continue;

            addList.add((Calendar) (cur.clone()));

            cur.add(Calendar.DAY_OF_YEAR, interval);

            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);
            break;
        case WEEKLY:
            /*
             * BYSECOND - for every listed second
             * BYMINUTE - for every listed minute
             * BYHOUR - for every listed hour
             * BYDAY - for every listed day
             * BYMONTHDAY - MAYBE once a month
             * BYYEARDAY - MAYBE once a year
             * BYMONTH - iff month matches
             *
             *  for each (INTERVAL)WEEK{
             *    if (byMonth && !month matches)
             *      curDay = set MONTH to DtStart in next matching month
             *
             *    if (byYearDay && !yearday matches)
             *      curDay = set date to next matching yearday
             *
             *    if (byMonthDay && !monthday matches)
             *      curDay = skip to next matching monthday
             *
             *    if (!byDay or FOREACH day in list)
             *      if (!byHour or FOREACH hour in list)
             *        if (!byMinute or FOREACH minute in list)
             *          if (!bySecond or FOREACH second in list)
             *            ----add to list----
             *
             *    check against BYSETPOS
             *
             *    curDay += 1 week
             * } while (count check & until check & rangeEnd check)
             *
             */
            if (!checkMonthList(cur))
                continue;

            if (!checkYearDayList(cur))
                continue;

            if (!checkMonthDayList(cur))
                continue;

            addList.add((Calendar) (cur.clone()));

            cur.add(Calendar.WEEK_OF_YEAR, interval);

            addList = expandDayListForWeekly(addList);
            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);
            break;
        case MONTHLY:
            if (!checkMonthList(cur))
                continue;

            if (!checkYearDayList(cur))
                continue;

            addList.add((Calendar) (cur.clone()));

            cur.set(Calendar.DAY_OF_MONTH, 1);
            cur.add(Calendar.MONTH, interval);
            int daysInMonth = cur.getActualMaximum(Calendar.DAY_OF_MONTH);
            cur.set(Calendar.DAY_OF_MONTH, Math.min(baseMonthDay, daysInMonth));

            addList = expandMonthDayList(addList);
            addList = expandDayListForMonthlyYearly(addList);
            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);

            break;
        case YEARLY:
            /*
             * BYSECOND
             * BYMINUTE
             * BYHOUR
             * BYDAY
             * BYMONTHDAY
             * BYYEARDAY
             * BYWEEKNO - specified week
             * BYMONTH - once
             */
            if (baseIsLeapDay) {
                // previously adding a year to a leap day will have rounded down to the 28th.
                // If this happened, we need to be sure that if we are back in a leap
                // year, it is back at 29th
                cur.set(Calendar.DAY_OF_MONTH, cur.getActualMaximum(Calendar.DAY_OF_MONTH));
            }
            if (ignoreYearForRecurrenceExpansion(cur, baseIsLeapDay)) {
                cur.add(Calendar.YEAR, interval);
                break;
            }
            addList.add((Calendar) (cur.clone()));

            cur.add(Calendar.YEAR, interval);

            addList = expandMonthList(addList);
            addList = expandYearDayList(addList);

            addList = expandMonthDayList(addList);
            addList = expandDayListForMonthlyYearly(addList);
            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);

            break;
        default:
            // MINUTELY and SECONDLY are intentionally not supported for performance reasons.
            return toRet;
        }

        addList = handleSetPos(addList);

        boolean noInstanceFound = true;
        boolean foundInstancePastEndDate = false;
        // add all the ones that match!
        for (Calendar addCal : addList) {
            Date toAdd = addCal.getTime();

            // We already counted DTSTART before the main loop, so don't
            // count it twice.
            if (toAdd.compareTo(dtStartDate) == 0) {
                noInstanceFound = false;
                continue;
            }

            // we still have expanded this instance, even if it isn't in our
            // current date window
            if (toAdd.after(dtStartDate))
                numInstancesExpanded++;

            if (!toAdd.after(rangeEndDate)) {
                if (!toAdd.before(earliestDate)) {
                    toRet.add(toAdd);
                    noInstanceFound = false;
                }
            } else {
                foundInstancePastEndDate = true;
                break;
            }

            if (maxInstancesExpanded > 0 && numInstancesExpanded >= maxInstancesExpanded)
                break;
        }

        // Detect invalid rule.  If the rule was invalid the current iteration, which is for the current
        // frequency interval, would have found no matching instance.  The next iteration will also find
        // no matching instance, and there is no need to keep iterating until we go past the hard end
        // time or COUNT/UNTIL limit.
        //
        // However, we have to make an exception for leap year.  An yearly rule looking for February 29th
        // will find no instance in up to 3 consecutive years before finding Feb 29th in the fourth year.
        //
        // So the invalid rule detection must look for at least 4 consecutive failed iterations.
        if (curIsAtOrAfterEarliestDate) {
            if (noInstanceFound)
                numConsecutiveIterationsWithoutMatchingInstance++;
            else
                numConsecutiveIterationsWithoutMatchingInstance = 0;
            if (numConsecutiveIterationsWithoutMatchingInstance >= 4) {
                ZimbraLog.calendar.warn("Invalid recurrence rule: " + toString());
                return toRet;
            }
        }

        pastHardEndTime = foundInstancePastEndDate || (noInstanceFound && curIsAfterEndDate);
    }

    return toRet;
}