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:org.opencastproject.util.DateTimeSupport.java

License:Educational Community License

/**
 * Forward to the next week day./* w w  w  .ja  v a2 s. com*/
 * <p/>
 * If it's Monday forwarding to Tuesday will add 1 day. If it's Friday forwarding to Thursday will go to next week's
 * Thursday which is adding 6 days. Forward to Monday if on Monday simply returns <code>time</code>.
 *
 * @param weekDay
 *          like described in {@link org.joda.time.DateTimeConstants}
 */
public static DateTime toNextWeekDay(DateTime time, int weekDay) {
    return time.getDayOfWeek() <= weekDay ? time.withDayOfWeek(weekDay)
            : time.plusWeeks(1).withDayOfWeek(weekDay);
}

From source file:org.openhab.binding.stiebelheatpump.internal.CommunicationService.java

License:Open Source License

/**
 * This method set the time of the heat pump to the current time
 * //from   w  w w .ja  v  a2  s . c o m
 * @return true if time has been updated
 */
public Map<String, String> setTime() throws StiebelHeatPumpException {

    startCommunication();
    Map<String, String> data = new HashMap<String, String>();

    Request timeRequest = null;

    for (Request request : heatPumpSettingConfiguration) {
        if (request.getName().equals("Time")) {
            timeRequest = request;
            break;
        }
    }

    if (timeRequest == null) {
        logger.warn("Could not find request definition for time settings! Skip setting time.");
        return data;
    }

    logger.debug("Loading current time data ...");
    try {
        // get time from heat pump
        byte[] requestMessage = createRequestMessage(timeRequest);
        byte[] response = getData(requestMessage);

        // get current time from local machine
        DateTime dt = DateTime.now();
        logger.debug("Current time is : {}", dt.toString());
        String weekday = Integer.toString(dt.getDayOfWeek() - 1);
        String day = Integer.toString(dt.getDayOfMonth());
        String month = Integer.toString(dt.getMonthOfYear());
        String year = Integer.toString(dt.getYearOfCentury());
        String seconds = Integer.toString(dt.getSecondOfMinute());
        String hours = Integer.toString(dt.getHourOfDay());
        String minutes = Integer.toString(dt.getMinuteOfHour());

        data = parser.parseRecords(response, timeRequest);

        boolean updateRequired = false;
        for (Map.Entry<String, String> entry : data.entrySet()) {
            String entryName = entry.getKey();
            String entryValue = entry.getValue();
            RecordDefinition currentRecord = null;

            for (RecordDefinition record : timeRequest.getRecordDefinitions()) {
                if (record.getName().equals(entryName)) {
                    currentRecord = record;
                    break;
                }
            }
            if (entryName.equals("WeekDay") && !entryValue.equals(weekday)) {
                updateRequired = true;
                response = parser.composeRecord(weekday, response, currentRecord);
                logger.debug("WeekDay needs update from {} to {}", entryValue, weekday);
                continue;
            }
            if (entryName.equals("Hours") && !entryValue.equals(hours)) {
                updateRequired = true;
                response = parser.composeRecord(hours, response, currentRecord);
                logger.debug("Hours needs update from {} to {}", entryValue, hours);
                continue;
            }
            if (entryName.equals("Minutes") && !entryValue.equals(minutes)) {
                updateRequired = true;
                response = parser.composeRecord(minutes, response, currentRecord);
                logger.debug("Minutes needs update from {} to {}", entryValue, minutes);
                continue;
            }
            if (entryName.equals("Seconds") && !entryValue.equals(seconds)) {
                updateRequired = true;
                response = parser.composeRecord(seconds, response, currentRecord);
                logger.debug("Seconds needs update from {} to {}", entryValue, seconds);
                continue;
            }
            if (entryName.equals("Year") && !entryValue.equals(year)) {
                updateRequired = true;
                response = parser.composeRecord(year, response, currentRecord);
                logger.debug("Year needs update from {} to {}", entryValue, year);
                continue;
            }
            if (entryName.equals("Month") && !entryValue.equals(month)) {
                updateRequired = true;
                response = parser.composeRecord(month, response, currentRecord);
                logger.debug("Month needs update from {} to {}", entryValue, month);
                continue;
            }
            if (entryName.equals("Day") && !entryValue.equals(day)) {
                updateRequired = true;
                response = parser.composeRecord(day, response, currentRecord);
                logger.debug("Day needs update from {} to {}", entryValue, day);
                continue;
            }
        }

        if (updateRequired) {
            Thread.sleep(WAITING_TIME_BETWEEN_REQUESTS);
            logger.info("Time need update. Set time to " + dt.toString());
            setData(response);

            Thread.sleep(WAITING_TIME_BETWEEN_REQUESTS);
            response = getData(requestMessage);
            data = parser.parseRecords(response, timeRequest);
            dt = DateTime.now();
            logger.debug("Current time is : {}", dt.toString());

        }
        return data;

    } catch (InterruptedException e) {
        throw new StiebelHeatPumpException(e.toString());
    }
}

From source file:org.opentestsystem.delivery.testadmin.scheduling.Scheduler.java

License:Open Source License

private Schedule generateScheduleStructure(final Schedule inSchedule,
        final Map<String, FacilityData> facilityData) {
    // build out the full Schedule structure
    // Create a List of ScheduledDay objects, one object for each day in the schedule
    // Each ScheduledDay object contains a List of ScheduledFacility objects, one for each Facility for this
    // institution
    // Each ScheduledFacility contains a list of ScheduledTimeSlots which are based upon the FacilityTimeSlot List
    // in each FacilityAvailability object
    // Each ScheduledTimeSlot contains a List of ScheduledSeat objects which are based off of the SeatConfigurations
    // setup in each FacilityTimeSlot

    Schedule scheduled = null;/*from  w w w  .ja v  a2  s .  com*/

    try {
        scheduled = (Schedule) inSchedule.clone();
    } catch (CloneNotSupportedException e) {
        throw new ScheduleException("Failed to clone schedule object, cannot generate schedule ", e);
    }

    TreeMap<DateTime, ScheduledDay> scheduledDaysMap = new TreeMap<DateTime, ScheduledDay>();

    DateTime scheduleStart = scheduled.getStartDate();
    DateTime scheduleEnd = scheduled.getEndDate();

    DateTime curTime = scheduleStart;

    // build all the ScheduledDay objects for this schedule
    while (curTime.isBefore(scheduleEnd) || curTime.equals(scheduleEnd)) {

        if (scheduled.isDoNotScheduleWeekends()) {
            if (curTime.getDayOfWeek() <= DateTimeConstants.FRIDAY) {
                ScheduledDay sday = new ScheduledDay();
                sday.setDay(curTime);

                scheduledDaysMap.put(curTime, sday);
            }
        } else {
            ScheduledDay sday = new ScheduledDay();
            sday.setDay(curTime);

            scheduledDaysMap.put(curTime, sday);
        }

        curTime = curTime.plusDays(1);
    }

    // go ahead and set the ScheduledDay objects into the schedule
    scheduled.setScheduledDays(new ArrayList<ScheduledDay>(scheduledDaysMap.values()));

    // iterate through all the FacilityData objects we have
    // each FacilityData has a Facility and a List of FacilityAvailabilities
    // Need to create a ScheduledFacility for each Facility for each ScheduledDay,
    // The ScheduledFacility has a list of ScheduledTimeSlots that need to be generated based upon
    // the FacilityAvailability objects which state from and to time. Basically, we need to match the date of the
    // ScheduledDay to the from->to range to ensure that the date of the current ScheduledDay falls in there.
    for (Map.Entry<String, FacilityData> entry : facilityData.entrySet()) {
        FacilityData facilData = entry.getValue();

        List<FacilityAvailability> availabilities = facilData.getAvailabilities();
        Facility facility = facilData.getFacility();

        // ensure that the seats are generated from the configurations
        facility.createSeatsFromConfiguration();

        for (FacilityAvailability avail : availabilities) {
            DateTime from = avail.getFromDate();
            DateTime to = avail.getToDate();

            List<FacilityTimeSlot> facilityTimeSlots = avail.getFacilityTimes();

            // iterate through ScheduledDays
            // if the day is in the range for the facility availability, then create a ScheduledFacility object
            // for that ScheduledDay

            for (DateTime schedDate : scheduledDaysMap.keySet()) {
                if ((from.isEqual(schedDate) || from.isBefore(schedDate))
                        && (to.isEqual(schedDate) || to.isAfter(schedDate))) {
                    ScheduledFacility schedFacil = new ScheduledFacility(facility);

                    // generate scheduled time slots for scheduledFacility

                    for (FacilityTimeSlot slot : facilityTimeSlots) {

                        slot.createSeatsFromConfiguration();

                        ScheduledTimeSlot schedSlot = new ScheduledTimeSlot(slot.getTimeSlot());

                        // create scheduled seats in slot
                        for (SeatConfiguration seatConfig : slot.getSeatConfigurations()) {
                            for (Seat seat : seatConfig.getSeats()) {
                                schedSlot.addSeat(new ScheduledSeat(seat));
                            }
                        }

                        // modify the date on the ScheduledTimeSlot to have the correct date (from schedDate) to go
                        // along with the specified time (from schedSlot)
                        // This will allow for correct ordering of time slots

                        DateTime newStartDate = new DateTime(schedDate.getYear(), schedDate.getMonthOfYear(),
                                schedDate.getDayOfMonth(), schedSlot.getStartTime().getHourOfDay(),
                                schedSlot.getStartTime().getMinuteOfHour());
                        DateTime newEndDate = new DateTime(schedDate.getYear(), schedDate.getMonthOfYear(),
                                schedDate.getDayOfMonth(), schedSlot.getEndTime().getHourOfDay(),
                                schedSlot.getEndTime().getMinuteOfHour());

                        schedSlot.setStartTime(newStartDate);
                        schedSlot.setEndTime(newEndDate);

                        schedFacil.addTimeSlot(schedSlot);
                    }

                    scheduledDaysMap.get(schedDate).addFacility(schedFacil);
                }
            }

        }

    }

    scheduled.generateOrderedTimeSlots();

    return scheduled;
}

From source file:org.oxymores.chronix.planbuilder.CalendarBuilder.java

License:Apache License

public static Calendar buildWorkDayCalendar(Application a, int year) {
    Calendar cal1 = new Calendar();
    cal1.setName("Week worked days");
    cal1.setDescription("All days from monday to friday for the whole year");
    cal1.setManualSequence(false);//  w ww .j a  va  2 s . c o  m
    a.addCalendar(cal1);

    DateTime d = new DateTime(year, 1, 1, 0, 0);
    while (d.getYear() == year) {
        if (d.getDayOfWeek() <= 5) {
            new CalendarDay(d.toString(OCCURRENCE_DAY_FORMAT), cal1);
        }
        d = d.plusDays(1);
    }

    return cal1;
}

From source file:org.patientview.service.impl.MessageManagerImpl.java

License:Open Source License

private String getFriendlyDateTime(Date date) {
    DateTime now = new DateTime();
    DateTime dateTime = new DateTime(date);

    if (dateTime.getYear() == now.getYear() && dateTime.getMonthOfYear() == now.getMonthOfYear()
            && dateTime.getDayOfWeek() == now.getDayOfWeek()) {
        return SHORT_DAY_FORMAT.format(date);
    } else {//from   w w  w  .jav  a2  s  .c  om
        return DATE_FORMAT.format(date);
    }
}

From source file:org.powertac.common.Rate.java

License:Apache License

/**
 * True just in case this Rate applies at the given DateTime, ignoring the
 * tier./* w w w.  j  a  va 2 s.c  o  m*/
 */
public boolean applies(AbstractInstant when) {
    boolean appliesWeekly = false;
    boolean appliesDaily = false;
    DateTime time = new DateTime(when, DateTimeZone.UTC);

    // check weekly applicability
    int day = time.getDayOfWeek();
    if (weeklyBegin == NO_TIME || weeklyEnd == NO_TIME) {
        appliesWeekly = true;
    } else if (weeklyEnd >= weeklyBegin) {
        appliesWeekly = (day >= weeklyBegin && day <= weeklyEnd);
    } else {
        appliesWeekly = (day >= weeklyBegin || day <= weeklyEnd);
    }

    // check daily applicability
    int hour = time.getHourOfDay();
    if (dailyBegin == NO_TIME || dailyEnd == NO_TIME) {
        appliesDaily = true;
    } else if (dailyEnd > dailyBegin) {
        // Interval does not span midnight
        appliesDaily = ((hour >= dailyBegin) && (hour <= dailyEnd));
    } else {
        // Interval spans midnight
        appliesDaily = ((hour >= dailyBegin) || (hour <= dailyEnd));
    }

    return (appliesWeekly && appliesDaily);
}

From source file:org.powertac.common.Tariff.java

License:Apache License

private int getTimeIndex(Instant when) {
    DateTime dt = new DateTime(when, DateTimeZone.UTC);
    int di = dt.getHourOfDay();
    if (isWeekly)
        di += 24 * (dt.getDayOfWeek() - 1);
    return di;/*from   w w w . j  ava2s . c  om*/
}

From source file:org.powertac.factoredcustomer.TimeseriesGenerator.java

License:Apache License

private double generateNextArima101x101(int timeslot) {
    /** R code/* w ww.  j  ava 2 s . c om*/
    boostTimeSeries = function(Xt, lambda, t, N, Xht, Xdt, gamma) {
    return (Xt + (lambda * ((log(t-26))^2/(log(N-26))^2) * ((1 - gamma) * Xht + gamma * Xdt)))
    }
    for (t in compRange) {                  
    Zf[t] = Y0 + Yd[D[t]] + Yh[H[t]] + phi1 * Zf[t-1] + Phi1 * Zf[t-24] #+ rnorm(1, 0, sigma^2) + 
                  theta1 * (Zf[t-1] - Zf[t-2]) + Theta1 * (Zf[t-24] - Zf[t-25]) + 
                  theta1 * Theta1 * (Zf[t-25] - Zf[t-26]) 
    Zbf[t] = boostTimeSeries(Zf[t], lambda, t, N, Yh[H[t]], Yd[D[t]], gamma) #+ rnorm(1, 0, sigma^2)
    }
    **/

    DateTime now = service.getTimeslotRepo().getTimeForIndex(timeslot).toDateTime();
    int day = now.getDayOfWeek(); // 1=Monday, 7=Sunday
    int hour = now.getHourOfDay(); // 0-23

    int t = timeslot;

    double logNext = Y0 + Yd[day - 1] + Yh[hour] + phi1 * getLog(t - 1) + Phi1 * getLog(t - 24)
            + theta1 * (getLog(t - 1) - getLog(t - 2)) + Theta1 * (getLog(t - 24) - getLog(t - 25))
            + theta1 * Theta1 * (getLog(t - 25) - getLog(t - 26));
    logNext = logNext + (lambda * (Math.pow(Math.log(t - 26), 2) / Math.pow(Math.log(FORECAST_HORIZON - 26), 2))
            * ((1 - gamma) * Yh[hour] + gamma * Yd[day - 1]));
    logNext = logNext + Math.pow(sigma, 2) * arimaNoise.nextGaussian();
    double next = Math.exp(logNext);
    if (Double.isNaN(next))
        throw new Error("Generated NaN as next time series element!");
    return next;
}

From source file:org.powertac.genco.MisoBuyer.java

License:Apache License

public void init(BrokerProxy proxy, int seedId, ContextService service) {
    log.info("init(" + seedId + ") " + getUsername());
    timeslotsOpen = Competition.currentCompetition().getTimeslotsOpen();
    this.brokerProxyService = proxy;
    //this.service = service;
    this.timeslotRepo = (TimeslotRepo) service.getBean("timeslotRepo");
    this.weatherReportRepo = (WeatherReportRepo) service.getBean("weatherReportRepo");
    this.weatherForecastRepo = (WeatherForecastRepo) service.getBean("weatherForecastRepo");
    RandomSeedRepo randomSeedRepo = (RandomSeedRepo) service.getBean("randomSeedRepo");
    // set up the random generator
    this.tsSeed = randomSeedRepo.getRandomSeed(MisoBuyer.class.getName(), seedId, "ts");
    // compute offsets for daily and weekly seasonal data
    int ts = timeslotRepo.currentSerialNumber();
    timeslotOffset = ts;/*  w w  w.  ja  v  a2s . c o m*/
    DateTime start = timeslotRepo.getDateTimeForIndex(ts);
    dailyOffset = start.getHourOfDay();
    weeklyOffset = (start.getDayOfWeek() - 1) * 24 + dailyOffset;
    timeseries = new ComposedTS();
    timeseries.initialize(ts);
}

From source file:org.projectforge.web.calendar.TimesheetEventsProvider.java

License:Open Source License

/**
 * @see org.projectforge.web.calendar.MyFullCalendarEventsProvider#buildEvents(org.joda.time.DateTime,
 *      org.joda.time.DateTime)//from  w w w  .  j  av a2 s.  c o  m
 */
@Override
protected void buildEvents(final DateTime start, final DateTime end) {
    totalDuration = 0;
    for (int i = 0; i < durationsPerDayOfMonth.length; i++) {
        durationsPerDayOfMonth[i] = 0;
    }
    for (int i = 0; i < durationsPerDayOfYear.length; i++) {
        durationsPerDayOfYear[i] = 0;
    }
    final Integer userId = calFilter.getTimesheetUserId();
    if (userId == null) {
        return;
    }
    breaksMap = new HashMap<String, TimesheetDO>();
    int breaksCounter = 0;
    final TimesheetFilter filter = new TimesheetFilter();
    filter.setUserId(userId);
    filter.setStartTime(start.toDate());
    filter.setStopTime(end.toDate());
    filter.setOrderType(OrderDirection.ASC);
    timesheets = timesheetDao.getList(filter);
    boolean longFormat = false;
    days = Days.daysBetween(start, end).getDays();
    if (days < 10) {
        // Week or day view:
        longFormat = true;
        month = null;
        firstDayOfMonth = null;
    } else {
        // Month view:
        final DateTime currentMonth = new DateTime(start.plusDays(10),
                ThreadLocalUserContext.getDateTimeZone()); // Now we're definitely in the right
        // month.
        month = currentMonth.getMonthOfYear();
        firstDayOfMonth = currentMonth.withDayOfMonth(1);
    }
    if (CollectionUtils.isEmpty(timesheets) == false) {
        DateTime lastStopTime = null;
        for (final TimesheetDO timesheet : timesheets) {
            final DateTime startTime = new DateTime(timesheet.getStartTime(),
                    ThreadLocalUserContext.getDateTimeZone());
            final DateTime stopTime = new DateTime(timesheet.getStopTime(),
                    ThreadLocalUserContext.getDateTimeZone());
            if (stopTime.isBefore(start) == true || startTime.isAfter(end) == true) {
                // Time sheet doesn't match time period start - end.
                continue;
            }
            if (calFilter.isShowBreaks() == true) {
                if (lastStopTime != null && DateHelper.isSameDay(stopTime, lastStopTime) == true
                        && startTime.getMillis() - lastStopTime.getMillis() > 60000) {
                    // Show breaks between time sheets of one day (> 60s).
                    final Event breakEvent = new Event();
                    breakEvent.setEditable(false);
                    final String breakId = String.valueOf(++breaksCounter);
                    breakEvent.setClassName(Const.BREAK_EVENT_CLASS_NAME).setId(breakId).setStart(lastStopTime)
                            .setEnd(startTime).setTitle(getString("timesheet.break"));
                    breakEvent.setTextColor("#666666").setBackgroundColor("#F9F9F9").setColor("#F9F9F9");
                    events.put(breakId, breakEvent);
                    final TimesheetDO breakTimesheet = new TimesheetDO().setStartDate(lastStopTime.toDate())
                            .setStopTime(startTime.getMillis());
                    breaksMap.put(breakId, breakTimesheet);
                }
                lastStopTime = stopTime;
            }
            final long duration = timesheet.getDuration();
            final MyWicketEvent event = new MyWicketEvent();
            final String id = "" + timesheet.getId();
            event.setClassName(Const.EVENT_CLASS_NAME);
            event.setId(id);
            event.setStart(startTime);
            event.setEnd(stopTime);
            final String title = CalendarHelper.getTitle(timesheet);
            if (longFormat == true) {
                // Week or day view:
                event.setTitle(title + "\n" + getToolTip(timesheet) + "\n" + formatDuration(duration, false));
            } else {
                // Month view:
                event.setTitle(title);
            }
            if (month != null && startTime.getMonthOfYear() != month && stopTime.getMonthOfYear() != month) {
                // Display time sheets of other month as grey blue:
                event.setTextColor("#222222").setBackgroundColor("#ACD9E8").setColor("#ACD9E8");
            }
            events.put(id, event);
            if (month == null || startTime.getMonthOfYear() == month) {
                totalDuration += duration;
                addDurationOfDay(startTime.getDayOfMonth(), duration);
            }
            final int dayOfYear = startTime.getDayOfYear();
            addDurationOfDayOfYear(dayOfYear, duration);
            event.setTooltip(getString("timesheet"),
                    new String[][] { { title }, { timesheet.getLocation(), getString("timesheet.location") },
                            { KostFormatter.formatLong(timesheet.getKost2()), getString("fibu.kost2") },
                            { TaskFormatter.getTaskPath(timesheet.getTaskId(), true, OutputType.PLAIN),
                                    getString("task") },
                            { timesheet.getDescription(), getString("description") } });
        }
    }
    if (calFilter.isShowStatistics() == true) {
        // Show statistics: duration of every day is shown as all day event.
        DateTime day = start;
        final Calendar cal = DateHelper.getCalendar();
        cal.setTime(start.toDate());
        final int numberOfDaysInYear = cal.getActualMaximum(Calendar.DAY_OF_YEAR);
        int paranoiaCounter = 0;
        do {
            if (++paranoiaCounter > 1000) {
                log.error(
                        "Paranoia counter exceeded! Dear developer, please have a look at the implementation of buildEvents.");
                break;
            }
            final int dayOfYear = day.getDayOfYear();
            final long duration = durationsPerDayOfYear[dayOfYear];
            final boolean firstDayOfWeek = day.getDayOfWeek() == ThreadLocalUserContext.getJodaFirstDayOfWeek();
            if (firstDayOfWeek == false && duration == 0) {
                day = day.plusDays(1);
                continue;
            }
            final Event event = new Event().setAllDay(true);
            final String id = "s-" + (dayOfYear);
            event.setId(id);
            event.setStart(day);
            final String durationString = formatDuration(duration, false);
            if (firstDayOfWeek == true) {
                // Show week of year at top of first day of week.
                long weekDuration = 0;
                for (short i = 0; i < 7; i++) {
                    int d = dayOfYear + i;
                    if (d > numberOfDaysInYear) {
                        d -= numberOfDaysInYear;
                    }
                    weekDuration += durationsPerDayOfYear[d];
                }
                final StringBuffer buf = new StringBuffer();
                buf.append(getString("calendar.weekOfYearShortLabel")).append(DateHelper.getWeekOfYear(day));
                if (days > 1 && weekDuration > 0) {
                    // Show total sum of durations over all time sheets of current week (only in week and month view).
                    buf.append(": ").append(formatDuration(weekDuration, false));
                }
                if (duration > 0) {
                    buf.append(", ").append(durationString);
                }
                event.setTitle(buf.toString());
            } else {
                event.setTitle(durationString);
            }
            event.setTextColor("#666666").setBackgroundColor("#F9F9F9").setColor("#F9F9F9");
            event.setEditable(false);
            events.put(id, event);
            day = day.plusDays(1);
        } while (day.isAfter(end) == false);
    }
}