Example usage for java.util Calendar WEEK_OF_YEAR

List of usage examples for java.util Calendar WEEK_OF_YEAR

Introduction

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

Prototype

int WEEK_OF_YEAR

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

Click Source Link

Document

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

Usage

From source file:org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static Object dateAdd(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {
    if (ArgList.length == 3) {
        try {//from w  w w  .ja va  2 s  .c om
            if (isNull(ArgList, new int[] { 0, 1, 2 })) {
                return null;
            } else if (isUndefined(ArgList, new int[] { 0, 1, 2 })) {
                return Context.getUndefinedValue();
            }
            java.util.Date dIn = (java.util.Date) Context.jsToJava(ArgList[0], java.util.Date.class);
            String strType = Context.toString(ArgList[1]).toLowerCase();
            int iValue = (int) Context.toNumber(ArgList[2]);
            Calendar cal = Calendar.getInstance();
            cal.setTime(dIn);
            if (strType.equals("y")) {
                cal.add(Calendar.YEAR, iValue);
            } else if (strType.equals("m")) {
                cal.add(Calendar.MONTH, iValue);
            } else if (strType.equals("d")) {
                cal.add(Calendar.DATE, iValue);
            } else if (strType.equals("w")) {
                cal.add(Calendar.WEEK_OF_YEAR, iValue);
            } else if (strType.equals("wd")) {
                int iOffset = 0;
                while (iOffset < iValue) {
                    int day = cal.get(Calendar.DAY_OF_WEEK);
                    cal.add(Calendar.DATE, 1);
                    if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
                        iOffset++;
                    }
                }
            } else if (strType.equals("hh")) {
                cal.add(Calendar.HOUR, iValue);
            } else if (strType.equals("mi")) {
                cal.add(Calendar.MINUTE, iValue);
            } else if (strType.equals("ss")) {
                cal.add(Calendar.SECOND, iValue);
            }
            return cal.getTime();
        } catch (Exception e) {
            throw Context.reportRuntimeError(e.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call dateAdd requires 3 arguments.");
    }
}

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

public static Object weekOfYear(ValueMetaInterface metaA, Object dataA) throws KettleValueException {
    if (dataA == null)
        return null;

    if (metaA.isDate()) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(metaA.getDate(dataA));
        return new Long(calendar.get(Calendar.WEEK_OF_YEAR));
    }/*from   w  w  w  . j a  va2  s  . c o m*/

    throw new KettleValueException("The 'weekOfYear' function only works with dates");
}

From source file:org.openossad.util.core.row.ValueDataUtil.java

public static Object weekOfYear(ValueMetaInterface metaA, Object dataA) throws OpenDESIGNERValueException {
    if (dataA == null)
        return null;

    if (metaA.isDate()) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(metaA.getDate(dataA));
        return new Long(calendar.get(Calendar.WEEK_OF_YEAR));
    }//  w  ww  . j a  v a2  s . com

    throw new OpenDESIGNERValueException("The 'weekOfYear' function only works with dates");
}

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  a  v a 2  s .  c o m*/
    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;
}

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

public static Object weekOfYearISO8601(ValueMetaInterface metaA, Object dataA) throws KettleValueException {
    if (dataA == null)
        return null;

    if (metaA.isDate()) {
        Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
        calendar.setMinimalDaysInFirstWeek(4);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(metaA.getDate(dataA));
        return new Long(calendar.get(Calendar.WEEK_OF_YEAR));
    }/*from   w  w  w . ja  v a  2 s  . com*/

    throw new KettleValueException("The 'weekOfYearISO8601' function only works with dates");
}

From source file:org.openossad.util.core.row.ValueDataUtil.java

public static Object weekOfYearISO8601(ValueMetaInterface metaA, Object dataA)
        throws OpenDESIGNERValueException {
    if (dataA == null)
        return null;

    if (metaA.isDate()) {
        Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
        calendar.setMinimalDaysInFirstWeek(4);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(metaA.getDate(dataA));
        return new Long(calendar.get(Calendar.WEEK_OF_YEAR));
    }//from  www .j a v  a2 s  .  c o m

    throw new OpenDESIGNERValueException("The 'weekOfYearISO8601' function only works with dates");
}

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

public static Object yearOfDateISO8601(ValueMetaInterface metaA, Object dataA) throws KettleValueException {
    if (dataA == null)
        return null;

    if (metaA.isDate()) {
        Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
        calendar.setMinimalDaysInFirstWeek(4);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(metaA.getDate(dataA));

        int week = calendar.get(Calendar.WEEK_OF_YEAR);
        int month = calendar.get(Calendar.MONTH);
        int year = calendar.get(Calendar.YEAR);

        // fix up for the year taking into account ISO8601 weeks
        if (week >= 52 && month == 0)
            year--;// ww w  .j  a  va2 s.  c  o  m
        if (week <= 2 && month == 11)
            year++;

        return new Long(year);
    }

    throw new KettleValueException("The 'yearOfDateISO8601' function only works with dates");
}

From source file:DateUtil.java

/**
 * Returns true if the two calendars represent dates that fall in the same
 * week, else false. A week here is defined by the Calendar.WEEK_OF_YEAR
 * package. Special provisions have been made to test weeks than may span the
 * end/beginning of a year, and returning true if the two calendars are
 * specifying dates within such a week, despite Calendar.WEEK_OF_YEAR being
 * unequal for the two Calendars./*w  w w.j  ava  2 s  .  c  o m*/
 * 
 * @param c1
 *          Calendar one.
 * @param c2
 *          Calendar two.
 * @return boolean.
 */
public static boolean inSameWeek(Calendar c1, Calendar c2) {
    if (inSameYear(c1, c2) && (c1.get(Calendar.WEEK_OF_YEAR) == c2.get(Calendar.WEEK_OF_YEAR)))
        return true;

    Calendar tmp;
    if (c1.before(c2)) {
        tmp = c2;
        c2 = c1;
        c1 = tmp;
    }

    int c1week = c1.get(Calendar.WEEK_OF_YEAR);
    int c2week = c1.get(Calendar.WEEK_OF_YEAR);

    if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) + 1) {
        if (c1week == c1.getActualMinimum(Calendar.WEEK_OF_YEAR)
                && c2week == c2.getActualMaximum(Calendar.WEEK_OF_YEAR)) {
            tmp = (Calendar) c2.clone();
            tmp.add(Calendar.DAY_OF_YEAR, 7);
            if (tmp.get(Calendar.WEEK_OF_YEAR) > c1week)
                return true;
        }
    }

    return false;
}

From source file:org.openossad.util.core.row.ValueDataUtil.java

public static Object yearOfDateISO8601(ValueMetaInterface metaA, Object dataA)
        throws OpenDESIGNERValueException {
    if (dataA == null)
        return null;

    if (metaA.isDate()) {
        Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
        calendar.setMinimalDaysInFirstWeek(4);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(metaA.getDate(dataA));

        int week = calendar.get(Calendar.WEEK_OF_YEAR);
        int month = calendar.get(Calendar.MONTH);
        int year = calendar.get(Calendar.YEAR);

        // fix up for the year taking into account ISO8601 weeks
        if (week >= 52 && month == 0)
            year--;//w w  w .ja v a2 s .  c o  m
        if (week <= 2 && month == 11)
            year++;

        return new Long(year);
    }

    throw new OpenDESIGNERValueException("The 'yearOfDateISO8601' function only works with dates");
}

From source file:com.aimluck.eip.project.ProjectTaskSelectData.java

/**
 * ??/*from  www  .j a va2  s .  c om*/
 *
 * @return ?
 */
public int getWeek(int days) {
    Calendar cal = (Calendar) calFrom.clone();
    cal.add(Calendar.DAY_OF_MONTH, days - 1);
    return cal.get(Calendar.WEEK_OF_YEAR);
}