List of usage examples for org.joda.time Days daysBetween
public static Days daysBetween(ReadablePartial start, ReadablePartial end)
Days
representing the number of whole days between the two specified partial datetimes. From source file:org.springframework.xd.analytics.metrics.redis.RedisAggregateCounterRepository.java
License:Apache License
/** * For each query, we need to convert the interval into two variations. One is the start and end points rounded to * the resolution (used to calculate the number of entries to be returned from the query). The second is the start * and end buckets we have to retrieve which may contain entries for the interval. For example, when querying * at day resolution, the number of entries is the number of Joda time days between the start (rounded down to a * day boundary) and the end plus one day (also rounded down). However, we need load the data from the buckets * from the month the start day occurs in to the month end day occurs in. These are then concatenated, using the * start day as the start index into the first array, and writing the total number of entries in sequence from that * point into the combined result counts array. *///from w ww . j a va 2s. c o m @Override public AggregateCount getCounts(String name, Interval interval, AggregateCountResolution resolution) { DateTime end = interval.getEnd(); Chronology c = interval.getChronology(); long[] counts; if (resolution == AggregateCountResolution.minute) { // Iterate through each hour in the interval and load the minutes for it MutableDateTime dt = new MutableDateTime(interval.getStart()); dt.setRounding(c.hourOfDay()); Duration step = Duration.standardHours(1); List<long[]> hours = new ArrayList<long[]>(); while (dt.isBefore(end) || dt.isEqual(end)) { hours.add(getMinCountsForHour(name, dt)); dt.add(step); } counts = MetricUtils.concatArrays(hours, interval.getStart().getMinuteOfHour(), interval.toPeriod().toStandardMinutes().getMinutes() + 1); } else if (resolution == AggregateCountResolution.hour) { DateTime cursor = new DateTime(c.dayOfMonth().roundFloor(interval.getStart().getMillis())); List<long[]> days = new ArrayList<long[]>(); Duration step = Duration.standardHours(24); while (cursor.isBefore(end)) { days.add(getHourCountsForDay(name, cursor)); cursor = cursor.plus(step); } counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(), interval.toPeriod().toStandardHours().getHours() + 1); } else if (resolution == AggregateCountResolution.day) { DateTime startDay = new DateTime(c.dayOfYear().roundFloor(interval.getStart().getMillis())); DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis())); int nDays = Days.daysBetween(startDay, endDay).getDays(); DateTime cursor = new DateTime(c.monthOfYear().roundFloor(interval.getStart().getMillis())); List<long[]> months = new ArrayList<long[]>(); DateTime endMonth = new DateTime( c.monthOfYear().roundCeiling(interval.getEnd().plusMonths(1).getMillis())); while (cursor.isBefore(endMonth)) { months.add(getDayCountsForMonth(name, cursor)); cursor = cursor.plusMonths(1); } counts = MetricUtils.concatArrays(months, interval.getStart().getDayOfMonth() - 1, nDays); } else if (resolution == AggregateCountResolution.month) { DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis())); DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis())); int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths(); DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis())); List<long[]> years = new ArrayList<long[]>(); DateTime endYear = new DateTime(c.year().roundCeiling(interval.getEnd().plusYears(1).getMillis())); while (cursor.isBefore(endYear)) { years.add(getMonthCountsForYear(name, cursor)); cursor = cursor.plusYears(1); } counts = MetricUtils.concatArrays(years, interval.getStart().getMonthOfYear() - 1, nMonths); } else if (resolution == AggregateCountResolution.year) { DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0); DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0); int nYears = Years.yearsBetween(startYear, endYear).getYears(); Map<String, Long> yearCounts = getYearCounts(name); counts = new long[nYears]; for (int i = 0; i < nYears; i++) { int year = startYear.plusYears(i).getYear(); Long count = yearCounts.get(Integer.toString(year)); if (count == null) { count = 0L; } counts[i] = count; } } else { throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution); } return new AggregateCount(name, interval, counts, resolution); }
From source file:org.squashtest.tm.domain.planning.StandardWorkloadCalendar.java
License:Open Source License
public float getWorkload(LocalDate start, LocalDate end) { if (end.isBefore(start)) { throw new IllegalArgumentException("dashboard.error.date"); }/*from w w w . j a v a2 s .c o m*/ LocalDate lstart = skipWeekendToMonday(start); LocalDate lend = truncateWeekendToLastFriday(end); // the following arises iif both days where in the weekend of the same week if (lend.isBefore(lstart)) { return Days.daysBetween(start, end).getDays() * WEEKEND_DAY_WORKLOAD; } int daysbetween = Days.daysBetween(lstart, lend).getDays() + 1; int adjustedDaysbetween = daysbetween + lstart.getDayOfWeek() - 1; int nbWeekend = adjustedDaysbetween / 7; int nbweekdays = daysbetween - nbWeekend * 2; return nbweekdays * BUSINESS_DAY_WORKLOAD; }
From source file:org.unitime.timetable.solver.studentsct.StudentSectioningDatabaseLoader.java
License:Apache License
public void load() { iProgress.setStatus("Loading input data ..."); org.hibernate.Session hibSession = null; Transaction tx = null;/*from w ww . j a va 2s .co m*/ try { hibSession = SessionDAO.getInstance().getSession(); hibSession.setCacheMode(CacheMode.IGNORE); hibSession.setFlushMode(FlushMode.MANUAL); tx = hibSession.beginTransaction(); Session session = null; if (iSessionId != null) { session = SessionDAO.getInstance().get(iSessionId); if (session != null) { iYear = session.getAcademicYear(); iTerm = session.getAcademicTerm(); iInitiative = session.getAcademicInitiative(); getModel().getProperties().setProperty("Data.Year", iYear); getModel().getProperties().setProperty("Data.Term", iTerm); getModel().getProperties().setProperty("Data.Initiative", iInitiative); } } else { session = Session.getSessionUsingInitiativeYearTerm(iInitiative, iYear, iTerm); if (session != null) { iSessionId = session.getUniqueId(); getModel().getProperties().setProperty("General.SessionId", String.valueOf(iSessionId)); } } if (session == null) throw new Exception("Session " + iInitiative + " " + iTerm + iYear + " not found!"); ApplicationProperties.setSessionId(session.getUniqueId()); if (iClassesFixedDate != null) { Date firstDay = DateUtils.getDate(1, session.getPatternStartMonth(), session.getSessionStartYear()); iClassesFixedDateIndex = Days.daysBetween(new LocalDate(firstDay), new LocalDate(iClassesFixedDate)) .getDays(); iDayOfWeekOffset = Constants.getDayOfWeek(firstDay); iProgress.info("Classes Fixed Date: " + iClassesFixedDate + " (date pattern index: " + iClassesFixedDateIndex + ")"); } iProgress.info("Loading data for " + iInitiative + " " + iTerm + iYear + "..."); if (getModel().getDistanceConflict() != null) TravelTime.populateTravelTimes(getModel().getDistanceConflict().getDistanceMetric(), iSessionId, hibSession); load(session, hibSession); if (!iUpdatedStudents.isEmpty()) { StudentSectioningQueue.studentChanged(hibSession, null, iSessionId, iUpdatedStudents); hibSession.flush(); } tx.commit(); } catch (Exception e) { iProgress.fatal("Unable to load sectioning problem, reason: " + e.getMessage(), e); sLog.error(e.getMessage(), e); tx.rollback(); } finally { // here we need to close the session since this code may run in a separate thread if (hibSession != null && hibSession.isOpen()) hibSession.close(); if (iValidationProvider != null) iValidationProvider.dispose(); if (iCriticalCoursesProvider != null) iCriticalCoursesProvider.dispose(); } }
From source file:org.vaadin.addons.tuningdatefield.TuningDateField.java
License:Apache License
protected CalendarItem[] buildDayItems() { LocalDate calendarFirstDay = getCalendarFirstDay(); LocalDate calendarLastDay = getCalendarLastDay(); LocalDate firstDayOfMonth = yearMonthDisplayed.toLocalDate(1); LocalDate lastDayOfMonth = yearMonthDisplayed.toLocalDate(1).dayOfMonth().withMaximumValue(); LocalDate today = LocalDate.now(); int numberOfDays = Days.daysBetween(calendarFirstDay, calendarLastDay).getDays() + 1; LocalDate date = calendarFirstDay; CalendarItem[] calendarItems = new CalendarItem[numberOfDays]; LocalDate currentValue = getLocalDate(); for (int i = 0; i < numberOfDays; i++, date = date.plusDays(1)) { calendarItems[i] = new CalendarItem(); calendarItems[i].setIndex(i);//from w ww. j av a2s . co m if (date.getMonthOfYear() == yearMonthDisplayed.getMonthOfYear()) { calendarItems[i].setRelativeDateIndex(date.getDayOfMonth()); } else { calendarItems[i].setRelativeDateIndex(-date.getDayOfMonth()); } String calendarItemContent = null; if (cellItemCustomizer != null) { calendarItemContent = cellItemCustomizer.renderDay(date, this); } // fallback to default value if (calendarItemContent == null) { calendarItemContent = Integer.toString(date.getDayOfMonth()); } calendarItems[i].setText(calendarItemContent); StringBuilder style = new StringBuilder(); if (date.equals(today)) { style.append("today "); } if (currentValue != null && date.equals(currentValue)) { style.append("selected "); } if (date.isBefore(firstDayOfMonth)) { style.append("previousmonth "); calendarItems[i].setEnabled(!isPreviousMonthDisabled()); } else if (date.isAfter(lastDayOfMonth)) { style.append("nextmonth "); calendarItems[i].setEnabled(!isNextMonthDisabled()); } else { style.append("currentmonth "); calendarItems[i].setEnabled(isDateEnabled(date)); } if (isWeekend(date)) { style.append("weekend "); } if (cellItemCustomizer != null) { String generatedStyle = cellItemCustomizer.getStyle(date, this); if (generatedStyle != null) { style.append(generatedStyle); style.append(" "); } String tooltip = cellItemCustomizer.getTooltip(date, this); if (tooltip != null) { calendarItems[i].setTooltip(tooltip); } } String computedStyle = style.toString(); if (!computedStyle.isEmpty()) { calendarItems[i].setStyle(computedStyle); } } return calendarItems; }
From source file:org.vaadin.addons.tuningdatefield.TuningDateField.java
License:Apache License
/** * @return the last day of the calendar. As there are 7 columns displayed, if the last day of month is not in the * last column, we fill next column items with days of next month. *///from www . j av a 2s . c o m private LocalDate getCalendarLastDay() { LocalDate lastDayOfMonth = yearMonthDisplayed.toLocalDate(1).dayOfMonth().withMaximumValue(); int calendarLastDayOfWeek = lastDayOfWeek; int numberOfDaysUntilLastDayOfWeek = (calendarLastDayOfWeek - lastDayOfMonth.getDayOfWeek() + 7) % 7; LocalDate lastDay = lastDayOfMonth.plusDays(numberOfDaysUntilLastDayOfWeek); if (isDisplayFixedNumberOfDayRows()) { // Always display 6 day rows int numberOfDays = Days.daysBetween(getCalendarFirstDay(), lastDay).getDays() + 1; if (numberOfDays / 7 < 5) { lastDay = lastDay.plusDays(14); } else if (numberOfDays / 7 < 6) { lastDay = lastDay.plusDays(7); } } return lastDay; }
From source file:org.wso2.analytics.esb.util.TimeRangeUtils.java
License:Open Source License
public static String getSuitableTimeRangeUnit(long from, long to) { DateTime fromTime = new DateTime(from); DateTime toTime = new DateTime(to); RangeUnit range;/*from w ww.j a v a 2s .co m*/ if (Months.monthsBetween(fromTime, toTime).getMonths() >= INTERVAL) { range = RangeUnit.MONTH; } else if (Days.daysBetween(fromTime, toTime).getDays() >= INTERVAL) { range = RangeUnit.DAY; } else if (Hours.hoursBetween(fromTime, toTime).getHours() >= INTERVAL) { range = RangeUnit.HOUR; } else if (Minutes.minutesBetween(fromTime, toTime).getMinutes() >= INTERVAL) { range = RangeUnit.MINUTE; } else { range = RangeUnit.SECOND; } return range.name(); }
From source file:org.zanata.client.commands.UpdateChecker.java
License:Open Source License
public boolean needToCheckUpdates(boolean interactiveMode) { DateTime today = new DateTime(); try {/*from w w w. j a va 2s.c om*/ if (!updateMarker.exists()) { createUpdateMarkerFile(updateMarker); console.printfln(_("update.marker.created"), updateMarker); console.printfln(_("update.marker.hint")); return true; } // read the content and see if we need to check Properties props = loadFileToProperties(updateMarker); DateTime lastCheckedDate = readLastCheckedDate(props); Days daysPassed = Days.daysBetween(lastCheckedDate, today); Frequency frequency = readFrequency(props); boolean timeToCheck = daysPassed.compareTo(frequency.days()) >= 0; boolean noAsking = readNoAsking(props); if (timeToCheck && !noAsking && interactiveMode) { console.printf(_("check.update.yes.no"), daysPassed.getDays()); String check = console.expectAnswerWithRetry(AnswerValidator.YES_NO); if (check.toLowerCase().startsWith("n")) { return false; } } return timeToCheck; } catch (Exception e) { log.debug("Error checking update marker file", e); log.warn("Error checking update marker file {}", updateMarker); log.warn("Please make sure its permission and content format"); return false; } }
From source file:org.zkoss.ganttz.data.criticalpath.CriticalPathCalculator.java
License:Open Source License
private void setEarliestStart(Node<T, D> node, int earliestStart, Constraint<GanttDate> constraint) { if (constraint != null) { GanttDate date = GanttDate.createFrom(initDate.plusDays(earliestStart)); date = constraint.applyTo(date); earliestStart = Days.daysBetween(initDate, LocalDate.fromDateFields(date.toDayRoundedDate())).getDays(); }//from w ww . j ava 2s . c om node.setEarliestStart(earliestStart); }
From source file:org.zkoss.ganttz.data.criticalpath.CriticalPathCalculator.java
License:Open Source License
private void setLatestFinish(Node<T, D> node, int latestFinish, Constraint<GanttDate> constraint) { if (constraint != null) { int duration = node.getDuration(); GanttDate date = GanttDate.createFrom(initDate.plusDays(latestFinish - duration)); date = constraint.applyTo(date); int daysBetween = Days.daysBetween(initDate, LocalDate.fromDateFields(date.toDayRoundedDate())) .getDays();/*from w w w.j av a 2s . c o m*/ latestFinish = daysBetween + duration; } node.setLatestFinish(latestFinish); }
From source file:org.zkoss.ganttz.data.criticalpath.Node.java
License:Open Source License
public int getDuration() { if (task == null) { return 0; } return Days.daysBetween(beginDate, endDate).getDays(); }