Example usage for org.joda.time DateTime getDayOfWeek

List of usage examples for org.joda.time DateTime getDayOfWeek

Introduction

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

Prototype

public int getDayOfWeek() 

Source Link

Document

Get the day of week field value.

Usage

From source file:com.nesscomputing.quartz.QuartzJob.java

License:Apache License

/**
 * Set the time-of-day when the first run of the job will take place.
 */// www.j  a  v a2 s . c o m
@SuppressWarnings("unchecked")
public final SelfType startTime(final DateTime when, final TimeSpan jitter) {
    // Find the current week day in the same time zone as the "when" time passed in.
    final DateTime now = new DateTime().withZone(when.getZone());

    final int startWeekDay = when.getDayOfWeek();
    final int currentWeekDay = now.getDayOfWeek();

    // ( x + n ) % n is x for x > 0 and n - x for x < 0.
    final int daysTilStart = (startWeekDay - currentWeekDay + DAYS_PER_WEEK) % DAYS_PER_WEEK;
    Preconditions.checkState(daysTilStart >= 0 && daysTilStart < DAYS_PER_WEEK,
            "daysTilStart must be 0..%s, but is %s", DAYS_PER_WEEK, daysTilStart);

    // same trick as above, add a full week in millis and do the modulo.
    final long millisecondsTilStart = (when.getMillisOfDay() - now.getMillisOfDay()
            + daysTilStart * MILLIS_PER_DAY + MILLIS_PER_WEEK) % MILLIS_PER_WEEK;
    Preconditions.checkState(millisecondsTilStart >= 0 && millisecondsTilStart < MILLIS_PER_WEEK,
            "millisecondsTilStart must be 0..%s, but is %s", MILLIS_PER_WEEK, millisecondsTilStart);

    this.delay = Duration.millis(
            (long) (ThreadLocalRandom.current().nextDouble() * jitter.getMillis()) + millisecondsTilStart);
    return (SelfType) this;
}

From source file:com.netflix.ice.basic.BasicDataManager.java

License:Apache License

private double[] getData(Interval interval, TagLists tagLists) throws ExecutionException {
    DateTime start = config.startDate;
    DateTime end = config.startDate;//from   w w w .ja  v a  2 s.c o m

    if (consolidateType == ConsolidateType.hourly) {
        start = interval.getStart().withDayOfMonth(1).withMillisOfDay(0);
        end = interval.getEnd();
    } else if (consolidateType == ConsolidateType.daily) {
        start = interval.getStart().withDayOfYear(1).withMillisOfDay(0);
        end = interval.getEnd();
    }

    int num = 0;
    if (consolidateType == ConsolidateType.hourly) {
        num = interval.toPeriod(PeriodType.hours()).getHours();
        if (interval.getStart().plusHours(num).isBefore(interval.getEnd()))
            num++;
    } else if (consolidateType == ConsolidateType.daily) {
        num = interval.toPeriod(PeriodType.days()).getDays();
        if (interval.getStart().plusDays(num).isBefore(interval.getEnd()))
            num++;
    } else if (consolidateType == ConsolidateType.weekly) {
        num = interval.toPeriod(PeriodType.weeks()).getWeeks();
        if (interval.getStart().plusWeeks(num).isBefore(interval.getEnd()))
            num++;
    } else if (consolidateType == ConsolidateType.monthly) {
        num = interval.toPeriod(PeriodType.months()).getMonths();
        if (interval.getStart().plusMonths(num).isBefore(interval.getEnd()))
            num++;
    }

    double[] result = new double[num];

    do {
        ReadOnlyData data = getReadOnlyData(start);

        int resultIndex = 0;
        int fromIndex = 0;

        if (interval.getStart().isBefore(start)) {
            if (consolidateType == ConsolidateType.hourly) {
                resultIndex = Hours.hoursBetween(interval.getStart(), start).getHours();
            } else if (consolidateType == ConsolidateType.daily) {
                resultIndex = Days.daysBetween(interval.getStart(), start).getDays();
            } else if (consolidateType == ConsolidateType.weekly) {
                resultIndex = Weeks.weeksBetween(interval.getStart(), start).getWeeks();
            } else if (consolidateType == ConsolidateType.monthly) {
                resultIndex = Months.monthsBetween(interval.getStart(), start).getMonths();
            }
        } else {
            if (consolidateType == ConsolidateType.hourly) {
                fromIndex = Hours.hoursBetween(start, interval.getStart()).getHours();
            } else if (consolidateType == ConsolidateType.daily) {
                fromIndex = Days.daysBetween(start, interval.getStart()).getDays();
            } else if (consolidateType == ConsolidateType.weekly) {
                fromIndex = Weeks.weeksBetween(start, interval.getStart()).getWeeks();
                if (start.getDayOfWeek() != interval.getStart().getDayOfWeek())
                    fromIndex++;
            } else if (consolidateType == ConsolidateType.monthly) {
                fromIndex = Months.monthsBetween(start, interval.getStart()).getMonths();
            }
        }

        List<Integer> columeIndexs = Lists.newArrayList();
        int columeIndex = 0;
        for (TagGroup tagGroup : data.getTagGroups()) {
            if (tagLists.contains(tagGroup))
                columeIndexs.add(columeIndex);
            columeIndex++;
        }
        while (resultIndex < num && fromIndex < data.getNum()) {
            double[] fromData = data.getData(fromIndex++);
            for (Integer cIndex : columeIndexs)
                result[resultIndex] += fromData[cIndex];
            resultIndex++;
        }

        if (consolidateType == ConsolidateType.hourly)
            start = start.plusMonths(1);
        else if (consolidateType == ConsolidateType.daily)
            start = start.plusYears(1);
        else
            break;
    } while (start.isBefore(end));

    return result;
}

From source file:com.netflix.ice.processor.BillingFileProcessor.java

License:Apache License

private void archiveSummary(Map<Product, ReadWriteData> dataMap, String prefix) throws Exception {

    DateTime monthDateTime = new DateTime(startMilli, DateTimeZone.UTC);

    for (Product product : dataMap.keySet()) {

        String prodName = product == null ? "all" : product.name;
        ReadWriteData data = dataMap.get(product);
        Collection<TagGroup> tagGroups = data.getTagGroups();

        // init daily, weekly and monthly
        List<Map<TagGroup, Double>> daily = Lists.newArrayList();
        List<Map<TagGroup, Double>> weekly = Lists.newArrayList();
        List<Map<TagGroup, Double>> monthly = Lists.newArrayList();

        // get last month data
        ReadWriteData lastMonthData = new DataWriter(prefix + "hourly_" + prodName + "_"
                + AwsUtils.monthDateFormat.print(monthDateTime.minusMonths(1)), true).getData();

        // aggregate to daily, weekly and monthly
        int dayOfWeek = monthDateTime.getDayOfWeek();
        int daysFromLastMonth = dayOfWeek - 1;
        int lastMonthNumHours = monthDateTime.minusMonths(1).dayOfMonth().getMaximumValue() * 24;
        for (int hour = 0 - daysFromLastMonth * 24; hour < data.getNum(); hour++) {
            if (hour < 0) {
                // handle data from last month, add to weekly
                Map<TagGroup, Double> prevData = lastMonthData.getData(lastMonthNumHours + hour);
                for (TagGroup tagGroup : tagGroups) {
                    Double v = prevData.get(tagGroup);
                    if (v != null && v != 0) {
                        addValue(weekly, 0, tagGroup, v);
                    }/*from w  ww.j a  v a  2  s .  co m*/
                }
            } else {
                // this month, add to weekly, monthly and daily
                Map<TagGroup, Double> map = data.getData(hour);

                for (TagGroup tagGroup : tagGroups) {
                    Double v = map.get(tagGroup);
                    if (v != null && v != 0) {
                        addValue(monthly, 0, tagGroup, v);
                        addValue(daily, hour / 24, tagGroup, v);
                        addValue(weekly, (hour + daysFromLastMonth * 24) / 24 / 7, tagGroup, v);
                    }
                }
            }
        }

        // archive daily
        int year = monthDateTime.getYear();
        DataWriter writer = new DataWriter(prefix + "daily_" + prodName + "_" + year, true);
        ReadWriteData dailyData = writer.getData();
        dailyData.setData(daily, monthDateTime.getDayOfYear() - 1, false);
        writer.archive();

        // archive monthly
        writer = new DataWriter(prefix + "monthly_" + prodName, true);
        ReadWriteData monthlyData = writer.getData();
        monthlyData.setData(monthly, Months.monthsBetween(config.startDate, monthDateTime).getMonths(), false);
        writer.archive();

        // archive weekly
        writer = new DataWriter(prefix + "weekly_" + prodName, true);
        ReadWriteData weeklyData = writer.getData();
        DateTime weekStart = monthDateTime.withDayOfWeek(1);
        int index;
        if (!weekStart.isAfter(config.startDate))
            index = 0;
        else
            index = Weeks.weeksBetween(config.startDate, weekStart).getWeeks()
                    + (config.startDate.dayOfWeek() == weekStart.dayOfWeek() ? 0 : 1);
        weeklyData.setData(weekly, index, true);
        writer.archive();
    }
}

From source file:com.pacoapp.paco.shared.scheduling.NonESMSignalGenerator.java

License:Open Source License

private DateTime scheduleWeekly(DateTime now) {
    DateTime nowMidnight = now.toDateMidnight().toDateTime();
    int nowDow = nowMidnight.getDayOfWeek(); // joda starts Monday, I start Sunday
    Integer nowDowIndex = Schedule.DAYS_OF_WEEK[nowDow == 7 ? 0 : nowDow]; // joda is 1 based, and starts on Monday. we are 0-based, Sunday-start
    if ((schedule.getWeekDaysScheduled() & nowDowIndex) == nowDowIndex) {
        DateTime nextTimeToday = getNextTimeToday(now, nowMidnight);
        if (nextTimeToday != null) {
            return nextTimeToday;
        }/*w w  w  .j a  v  a  2  s.  c om*/
    }
    DateTime nextDay = getNextScheduleDay(nowMidnight.plusDays(1));
    return getFirstScheduledTimeOnDay(nextDay);
}

From source file:com.pacoapp.paco.shared.scheduling.NonESMSignalGenerator.java

License:Open Source License

private DateTime getNextScheduleDay(DateTime midnightTomorrow) {

    switch (schedule.getScheduleType()) {
    case Schedule.DAILY:
        return nextRepeatDaily(midnightTomorrow);

    case Schedule.WEEKDAY:
        int tomorrowDOW = midnightTomorrow.getDayOfWeek();
        if (tomorrowDOW > DateTimeConstants.FRIDAY) {
            return midnightTomorrow.plusDays(8 - tomorrowDOW);
        } else {/*from w  w  w  .  j  a v a  2 s  .com*/
            return midnightTomorrow;
        }

    case Schedule.WEEKLY:
        int scheduleDays = schedule.getWeekDaysScheduled();
        if (scheduleDays == 0) {
            return null;
        }
        for (int i = 0; i < 8; i++) { // go at least to the same day next week.
            int midnightTomorrowDOW = midnightTomorrow.getDayOfWeek();
            Integer nowDowIndex = Schedule.DAYS_OF_WEEK[midnightTomorrowDOW == 7 ? 0 : midnightTomorrowDOW]; // joda is 1 based & counts Monday as first day of the week so Sunday is 7 instead of 0.
            if ((scheduleDays & nowDowIndex) == nowDowIndex) {
                return nextRepeatWeekly(midnightTomorrow);
            }
            midnightTomorrow = midnightTomorrow.plusDays(1);

        }
        throw new IllegalStateException("Cannot get to here. Weekly must repeat at least once a week");

    case Schedule.MONTHLY:
        if (schedule.getByDayOfMonth()) {
            int midnightDOM = midnightTomorrow.getDayOfMonth();
            int scheduledDOM = schedule.getDayOfMonth();
            if (midnightDOM == scheduledDOM) {
                return midnightTomorrow;
            } else if (midnightDOM > scheduledDOM) {
                MutableDateTime mutableDateTime = midnightTomorrow.plusMonths(1).toMutableDateTime();
                mutableDateTime.setDayOfMonth(scheduledDOM);
                return nextRepeatMonthly(mutableDateTime.toDateTime());
            } else {
                return nextRepeatMonthly(midnightTomorrow.plusDays(scheduledDOM - midnightDOM));
            }
        } else {
            Integer nthOfMonth = schedule.getNthOfMonth();
            Integer dow = getDOWFromIndexedValue(); // only one selection, so take log2 to get index of dow
            DateMidnight nthDowDate = getNthDOWOfMonth(midnightTomorrow, nthOfMonth, dow).toDateMidnight();
            DateTime returnDate = null;
            if (nthDowDate.equals(midnightTomorrow)) {
                returnDate = midnightTomorrow;
            } else if (nthDowDate.isAfter(midnightTomorrow)) {
                returnDate = nthDowDate.toDateTime();
            } else {
                returnDate = getNthDOWOfMonth(midnightTomorrow.plusMonths(1), nthOfMonth, dow).toDateTime();
            }
            return nextRepeatMonthly(returnDate);
        }
    default:
        throw new IllegalStateException("Schedule has an unknown type: " + schedule.getScheduleType());
    }
}

From source file:com.pandits.opensource.JodaTimeUtil.java

License:Open Source License

public int getDayOfTheWeek(long timeInMillis, TimeZone timeZone) {
    DateTime dateTime = createDateTime(timeInMillis, timeZone);
    return dateTime.getDayOfWeek();
}

From source file:com.pureblue.quant.util.frequency.Weekly.java

@Override
public DateTime periodBegin(DateTime time) {
    int timeDifference = time.getDayOfWeek() - day.toJodaTimeValue();
    if (timeDifference < 0) {
        timeDifference += 7;/*from w  ww .  jav a 2  s  .c om*/
    }
    DateTime startDay = time.minusDays(timeDifference);
    DateTime weekStart = new DateTime(startDay.getYear(), startDay.getMonthOfYear(), startDay.getDayOfMonth(),
            dayStartTime.getHourOfDay(), dayStartTime.getMinuteOfHour(), dayStartTime.getSecondOfMinute(),
            dayStartTime.getMillisOfSecond(), startDay.getZone());
    if (weekStart.isAfter(time)) {
        return weekStart.minusWeeks(1);
    } else {
        return weekStart;
    }
}

From source file:com.qcadoo.mes.basic.shift.Shift.java

License:Open Source License

/**
 * Check if this shift will be working at given date and time. This method is aware of timetable exceptions
 * /*  ww w.j  a v a  2s .c o m*/
 * @param date
 * @return true if this shift will be working at given date and time.
 * 
 * @deprecated use worksAt(DateTime) if you want to check if shift works at given date and time, or works(LocalDate) if all
 *             you want is just check if shift works at given day.
 */
@Deprecated
public boolean worksAt(final Date date) {
    DateTime dateTime = new DateTime(date);
    return (worksAt(dateTime.getDayOfWeek(), dateTime.toLocalTime())
            && !timetableExceptions.hasFreeTimeAt(date)) || timetableExceptions.hasWorkTimeAt(date);
}

From source file:com.qcadoo.mes.basic.shift.Shift.java

License:Open Source License

/**
 * Returns date range containing given date. This method IS AWARE of timetable exceptions.
 * /*w  w w  .j  ava  2  s  . com*/
 * <b>Be aware</b> - this method doesn't compose returned date range with the timetable exclusions/inclusions. This means that
 * if you have a shift which works at Monday from 8:00-16:00 and there is defined work time exclusion from 12:00-20:00 and you
 * ask for 10:00 then you will get date range from 8:00-16:00 (as in plan). But if you ask for 14:00 you will get
 * Optional.absent().
 * 
 * @param date
 *            date with time for which work dates range you want to find.
 * @return
 */
public Optional<DateRange> findWorkTimeAt(final Date date) {
    if (timetableExceptions.hasFreeTimeAt(date)) {
        return Optional.absent();
    }
    DateTime dateTime = new DateTime(date);
    Optional<TimeRange> maybeTimeRangeFromPlan = findWorkTimeAt(dateTime.getDayOfWeek(),
            dateTime.toLocalTime());
    for (TimeRange timeRangeFromPlan : maybeTimeRangeFromPlan.asSet()) {
        return Optional.of(buildDateRangeFrom(timeRangeFromPlan, date));
    }
    return timetableExceptions.findDateRangeFor(TimetableExceptionType.WORK_TIME, date);
}

From source file:com.qcadoo.mes.basic.ShiftsServiceImpl.java

License:Open Source License

public Collection<ShiftHour> getHourForDay(final Entity shift, final Date dateFrom, final Date dateTo,
        final String day, final int offset) {
    if ((Boolean) shift.getField(day + WORKING_LITERAL)
            && StringUtils.hasText(shift.getStringField(day + HOURS_LITERAL))) {
        List<ShiftHour> hours = new ArrayList<ShiftHour>();

        LocalTime[][] dayHours = convertDayHoursToInt(shift.getStringField(day + HOURS_LITERAL));

        DateTime from = new DateTime(dateFrom).withSecondOfMinute(0);
        DateTime to = new DateTime(dateTo);

        DateTime current = from.plusDays(offset - from.getDayOfWeek());

        if (current.compareTo(from) < 0) {
            current = current.plusDays(7);
        }//  w w  w .  j av  a 2s  .c o m

        while (current.compareTo(to) <= 0) {
            for (LocalTime[] dayHour : dayHours) {
                hours.add(new ShiftHour(
                        current.withHourOfDay(dayHour[0].getHourOfDay())
                                .withMinuteOfHour(dayHour[0].getMinuteOfHour()).toDate(),
                        current.withHourOfDay(dayHour[1].getHourOfDay())
                                .withMinuteOfHour(dayHour[1].getMinuteOfHour()).toDate()));
            }
            current = current.plusDays(7);
        }

        return hours;
    } else {
        return Collections.emptyList();
    }
}