public List<Integer> getAverageGlucoseReadingsByWeek() { JodaTimeAndroid.init(mContext); DateTime maxDateTime = new DateTime(realm.where(GlucoseReading.class).maximumDate("created").getTime()); DateTime minDateTime = new DateTime(realm.where(GlucoseReading.class).minimumDate("created").getTime()); DateTime currentDateTime = minDateTime; DateTime newDateTime = minDateTime; ArrayList<Integer> averageReadings = new ArrayList<Integer>(); // The number of weeks is at least 1 since we do have average for the current week even if incomplete int weeksNumber = Weeks.weeksBetween(minDateTime, maxDateTime).getWeeks() + 1; for (int i = 0; i < weeksNumber; i++) { newDateTime = currentDateTime.plusWeeks(1); RealmResults<GlucoseReading> readings = realm.where(GlucoseReading.class) .between("created", currentDateTime.toDate(), newDateTime.toDate()) .findAll(); averageReadings.add(((int) readings.average("reading"))); currentDateTime = newDateTime; } return averageReadings; }
public List<String> getGlucoseDatetimesByWeek() { JodaTimeAndroid.init(mContext); DateTime maxDateTime = new DateTime(realm.where(GlucoseReading.class).maximumDate("created").getTime()); DateTime minDateTime = new DateTime(realm.where(GlucoseReading.class).minimumDate("created").getTime()); DateTime currentDateTime = minDateTime; DateTime newDateTime = minDateTime; ArrayList<String> finalWeeks = new ArrayList<String>(); // The number of weeks is at least 1 since we do have average for the current week even if incomplete int weeksNumber = Weeks.weeksBetween(minDateTime, maxDateTime).getWeeks() + 1; DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); for (int i = 0; i < weeksNumber; i++) { newDateTime = currentDateTime.plusWeeks(1); finalWeeks.add(inputFormat.format(newDateTime.toDate())); currentDateTime = newDateTime; } return finalWeeks; }
/** * Returns the number of weeks between two dates. */ @Function("WEEKS") @FunctionParameters({ @FunctionParameter("startDate"), @FunctionParameter("endDate")}) public Integer WEEKS(Object startDate, Object endDate){ Date startDateObj = convertDateObject(startDate); if(startDateObj==null) { logCannotConvertToDate(); return null; } Date endDateObj = convertDateObject(endDate); if(endDateObj==null){ logCannotConvertToDate(); return null; } else{ LocalDate dt1=new LocalDate(startDateObj); LocalDate dt2=new LocalDate(endDateObj); return Weeks.weeksBetween(dt1, dt2).getWeeks(); } }
@Override public Object create(Object request, SpecimenContext context) { if (!(request instanceof SpecimenType)) { return new NoSpecimen(); } SpecimenType type = (SpecimenType) request; if (!BaseSingleFieldPeriod.class.isAssignableFrom(type.getRawType())) { return new NoSpecimen(); } Duration duration = (Duration) context.resolve(Duration.class); if (type.equals(Seconds.class)) return Seconds.seconds(Math.max(1, (int) duration.getStandardSeconds())); if (type.equals(Minutes.class)) return Minutes.minutes(Math.max(1, (int) duration.getStandardMinutes())); if (type.equals(Hours.class)) return Hours.hours(Math.max(1, (int) duration.getStandardHours())); if (type.equals(Days.class)) return Days.days(Math.max(1, (int) duration.getStandardDays())); if (type.equals(Weeks.class)) return Weeks.weeks(Math.max(1, (int) duration.getStandardDays() / 7)); if (type.equals(Months.class)) return Months.months(Math.max(1, (int) duration.getStandardDays() / 30)); if (type.equals(Years.class)) return Years.years(Math.max(1, (int) duration.getStandardDays() / 365)); return new NoSpecimen(); }
/** * Obtain the indicators from the statistics and stores them into the im * * @param im indicatorMap to store the indicators * @param statistics statistics of the git. */ private void storeAllMeasures(IndicatorsMap im, GitLogStatistics statistics) { DateTime dt = new DateTime(statistics.firstCommitDate); Months months = Months.monthsBetween(dt, new DateTime()); Weeks weeks = Weeks.weeksBetween(dt, new DateTime()); im.add("git average-commits-per-month", (double) statistics.totalCommits / months.getMonths()); im.add("git average-commits-per-week", (double) statistics.totalCommits / weeks.getWeeks()); im.add("git average-commits-per-committer", (double) statistics.totalCommits / statistics.totalCommitters); im.add("git average-files-changed-per-committer", (double) statistics.totalFilesChanged / statistics.totalCommitters); im.add("git average-lines-added-per-commmit", (double) statistics.totalLinesAdded / statistics.totalCommits); im.add("git average-lines-removed-per-commit", (double) statistics.totalLinesRemoved / statistics.totalCommits); im.add("git average-files-changed-per-commit", (double) statistics.totalFilesChanged / statistics.totalCommits); im.add("git distribution-commits-by-hour", RiskDataType.DISTRIBUTION, getDistribution(statistics.commitsByHour, statistics.totalCommits)); im.add("git distribution-commits-by-weekday", RiskDataType.DISTRIBUTION, getDistribution(statistics.commitsByWeekday, statistics.totalCommits)); }
@Override public List<Prediction> predict(PredictorState state, UtilizationHistory history, int maxCapacity) { Optional<Utilization> latest = history.getLatest(); if (!latest.isPresent()) return Collections.emptyList(); DateTime now = state.latestUtilization = latest.get().timestamp; List<List<Prediction>> groupedByWeek = Stream.of(Weeks.weeks(1), Weeks.weeks(2), Weeks.weeks(3)) .map(offset -> { DateTime start = now.minus(offset); DateTime end = start.plus(PredictionRepository.PREDICTION_WINDOW); List<Utilization> utilizations = history.getRange(start, end); return utilizations.stream() .map(u -> new Prediction(u.timestamp.plus(offset), u.spacesAvailable)) .collect(Collectors.toList()); }) .collect(Collectors.toList()); List<List<Prediction>> groupedByTimeOfDay = ListUtil.transpose(groupedByWeek); return groupedByTimeOfDay.stream() .map(this::reduce) .collect(Collectors.toList()); }
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_knell); ButterKnife.bind(this); Birthday birthday = getBirthdayManager().get(); DateTime birDateTime = new DateTime(birthday.year, birthday.month, birthday.day, 0, 0); Days days = Days.daysBetween(birDateTime, DateTime.now()); Hours hours = Hours.hoursBetween(birDateTime, DateTime.now()); Minutes minutes = Minutes.minutesBetween(birDateTime, DateTime.now()); Weeks weeks = Weeks.weeksBetween(birDateTime, DateTime.now()); Years years = Years.yearsBetween(birDateTime, DateTime.now()); Months months = Months.monthsBetween(birDateTime, DateTime.now()); Timber.d("onCreate: 年:%d", years.getYears()); Timber.d("onCreate: 月:%d", months.getMonths()); Timber.d("onCreate: 周:%d", weeks.getWeeks()); Timber.d("onCreate: 天数为:%d", days.getDays()); Timber.d("onCreate: 小时数为:%d", hours.getHours()); Timber.d("onCreate: 分钟数为:%d", minutes.getMinutes()); tvYear.setText(String.valueOf(years.getYears())); tvMonth.setText(String.valueOf(months.getMonths())); tvWeek.setText(String.valueOf(weeks.getWeeks())); tvDay.setText(String.valueOf(days.getDays())); tvHour.setText(String.valueOf(hours.getHours())); tvMinute.setText(String.valueOf(minutes.getMinutes())); }
@Override public void execute(MessageReceivedEvent event, String[] args) { DateTime current = new DateTime(DateTimeZone.forID("America/Montreal")); while (current.getDayOfWeek() != DateTimeConstants.TUESDAY) { current = current.minusDays(1); } int weeks = Weeks.weeksBetween(Utils.startDateMythicPlus, current).getWeeks(); String[] weekAffixes = Utils.mythicPlusAffixes[weeks % 12]; event.getChannel().sendMessage(Utils.createMythicEmbed(bot, event.getGuild(), weekAffixes).build()).queue(); }
@Override public void execute(MessageReceivedEvent event, String[] args) { DateTime current = new DateTime(DateTimeZone.forID("America/Montreal")); if (current.getDayOfWeek() == DateTimeConstants.TUESDAY) { current = current.plusDays(1); } while (current.getDayOfWeek() != DateTimeConstants.TUESDAY) { current = current.plusDays(1); } int weeks = Weeks.weeksBetween(Utils.startDateMythicPlus, current).getWeeks(); String[] weekAffixes = Utils.mythicPlusAffixes[weeks % 12]; event.getChannel().sendMessage(Utils.createMythicEmbed(bot, event.getGuild(), weekAffixes).build()).queue(); }
public static ReadablePeriod parsePeriodString(String periodStr) { ReadablePeriod period; char periodUnit = periodStr.charAt(periodStr.length() - 1); if (periodUnit == 'n') { return null; } int periodInt = Integer.parseInt(periodStr.substring(0, periodStr.length() - 1)); switch (periodUnit) { case 'M': period = Months.months(periodInt); break; case 'w': period = Weeks.weeks(periodInt); break; case 'd': period = Days.days(periodInt); break; case 'h': period = Hours.hours(periodInt); break; case 'm': period = Minutes.minutes(periodInt); break; case 's': period = Seconds.seconds(periodInt); break; default: throw new IllegalArgumentException("Invalid schedule period unit '" + periodUnit); } return period; }
public static ReadablePeriod parsePeriodString(String periodStr) { ReadablePeriod period; char periodUnit = periodStr.charAt(periodStr.length() - 1); if (periodStr.equals("null") || periodUnit == 'n') { return null; } int periodInt = Integer.parseInt(periodStr.substring(0, periodStr.length() - 1)); switch (periodUnit) { case 'y': period = Years.years(periodInt); break; case 'M': period = Months.months(periodInt); break; case 'w': period = Weeks.weeks(periodInt); break; case 'd': period = Days.days(periodInt); break; case 'h': period = Hours.hours(periodInt); break; case 'm': period = Minutes.minutes(periodInt); break; case 's': period = Seconds.seconds(periodInt); break; default: throw new IllegalArgumentException("Invalid schedule period unit '" + periodUnit); } return period; }
public static int getTimeSteps(int tempRes, int startTime, int endTime) { if (startTime > endTime) { return 0; } int timeSteps = 0; DateTime start = new DateTime(((long)startTime)*1000, DateTimeZone.UTC); DateTime end = new DateTime(((long)endTime)*1000, DateTimeZone.UTC); switch(tempRes) { case FrameworkUtils.HOUR: timeSteps = Hours.hoursBetween(start, end).getHours(); break; case FrameworkUtils.DAY: timeSteps = Days.daysBetween(start, end).getDays(); break; case FrameworkUtils.WEEK: timeSteps = Weeks.weeksBetween(start, end).getWeeks(); break; case FrameworkUtils.MONTH: timeSteps = Months.monthsBetween(start, end).getMonths(); break; case FrameworkUtils.YEAR: timeSteps = Years.yearsBetween(start, end).getYears(); break; default: timeSteps = Hours.hoursBetween(start, end).getHours(); break; } timeSteps++; return timeSteps; }
public static int getDeltaSinceEpoch(int time, int tempRes) { int delta = 0; // Epoch MutableDateTime epoch = new MutableDateTime(); epoch.setDate(0); DateTime dt = new DateTime(time*1000, DateTimeZone.UTC); switch(tempRes) { case FrameworkUtils.HOUR: Hours hours = Hours.hoursBetween(epoch, dt); delta = hours.getHours(); break; case FrameworkUtils.DAY: Days days = Days.daysBetween(epoch, dt); delta = days.getDays(); break; case FrameworkUtils.WEEK: Weeks weeks = Weeks.weeksBetween(epoch, dt); delta = weeks.getWeeks(); break; case FrameworkUtils.MONTH: Months months = Months.monthsBetween(epoch, dt); delta = months.getMonths(); break; case FrameworkUtils.YEAR: Years years = Years.yearsBetween(epoch, dt); delta = years.getYears(); break; default: hours = Hours.hoursBetween(epoch, dt); delta = hours.getHours(); break; } return delta; }
@Test public void testParseOneWeekAgo() { PointInTime expectedLastWeek = PointInTime.today().subtract(Weeks.weeks(1)); PointInTime lastWeek = RelativeDateTimeFormat.parse("TODAY-7"); assertThat(lastWeek, is(expectedLastWeek)); assertThat(lastWeek.getPrecision(), is(Precision.DATE)); lastWeek = RelativeDateTimeFormat.parse("Today-7"); assertThat(lastWeek, is(expectedLastWeek)); assertThat(lastWeek.getPrecision(), is(Precision.DATE)); lastWeek = RelativeDateTimeFormat.parse("T-7"); assertThat(lastWeek, is(expectedLastWeek)); assertThat(lastWeek.getPrecision(), is(Precision.DATE)); lastWeek = RelativeDateTimeFormat.parse("t-7"); assertThat(lastWeek, is(expectedLastWeek)); assertThat(lastWeek.getPrecision(), is(Precision.DATE)); lastWeek = RelativeDateTimeFormat.parse("t-1W"); assertThat(lastWeek, is(expectedLastWeek)); assertThat(lastWeek.getPrecision(), is(Precision.DATE)); lastWeek = RelativeDateTimeFormat.parse("t-1w"); assertThat(lastWeek, is(expectedLastWeek)); assertThat(lastWeek.getPrecision(), is(Precision.DATE)); }
public LocalDateTime resolve(LocalDateTime base) { if (this.duration==null || this.durationUnit==null) { return null; } ReadablePeriod period = null; if (DAYS.equals(durationUnit)) { period = Days.days(getDurationAsInt()); } else if (WEEKS.equals(durationUnit)) { period = Weeks.weeks(getDurationAsInt()); } else if (HOURS.equals(durationUnit)) { period = Hours.hours(getDurationAsInt()); } else if (MONTHS.equals(durationUnit)) { period = Months.months(getDurationAsInt()); } else if (YEARS.equals(durationUnit)) { period = Years.years(getDurationAsInt()); } else if (MINUTES.equals(durationUnit)) { period = Minutes.minutes(getDurationAsInt()); } else { return null; } LocalDateTime time = base.plus(period); if (atHour!=null) { LocalDateTime atTime = time.withTime(atHour, atMinute!=null ? atMinute : 0, 0, 0); if (atTime.isBefore(time)) { time = atTime.plusDays(1); } else { time = atTime; } } else if (isDayResolutionOrBigger()) { time = time.withTime(23, 59, 59, 999); } return time; }
/** * Calculates the difference between two times, given as long values, and * returns the period between them in the specified <code>units</code>. The * units value must be one of: * <pre> * {@link #MILLISECONDS} * {@link #SECONDS} * {@link #MINUTES} * {@link #HOURS} * {@link #DAYS} * {@link #WEEKS} * {@link #MONTHS} * {@link #YEARS} * </pre> * All values will be returned as the absolute value of the difference. * * @param arg1 The value to use as the minuend. * @param arg2 The value to use as the subtrahend. * @param units The time units to use for expressing the difference. * @return The long value of the difference between the arguments in the * specified units. */ public static long period(long arg1, long arg2, int units) { long delta = arg1 - arg2; DateTime start = new DateTime(arg1); DateTime end = new DateTime(arg2); // Compute delta into appropriate units switch(units) { case YEARS: delta = Years.yearsBetween(start, end).getYears(); break; case MONTHS: delta = Months.monthsBetween(start, end).getMonths(); break; case WEEKS: delta = Weeks.weeksBetween(start, end).getWeeks(); break; case DAYS: delta = Days.daysBetween(start, end).getDays(); break; case HOURS: delta = Hours.hoursBetween(start, end).getHours(); break; case MINUTES: delta = Minutes.minutesBetween(start, end).getMinutes(); break; case SECONDS: delta = Double.valueOf(Math.floor(delta/1000.0)).longValue(); break; case MILLISECONDS: // Here for completeness but already calculated break; default: throw new IllegalArgumentException("Invalid units: " + units + " See Functions.difference(Calendar,Calendar)" + " for allowed values"); } return Math.abs(delta); }
/** * Convert comparison mode to Period * @param compareMode * @return */ public static Period getBaselinePeriod(COMPARE_MODE compareMode) { switch (compareMode) { case Wo2W: return Weeks.TWO.toPeriod(); case Wo3W: return Weeks.THREE.toPeriod(); case Wo4W: return Weeks.weeks(4).toPeriod(); case WoW: default: return Weeks.ONE.toPeriod(); } }
public static Period getBaselinePeriod(AlertConfigBean.COMPARE_MODE compareMode) { switch (compareMode) { case Wo2W: return Weeks.TWO.toPeriod(); case Wo3W: return Weeks.THREE.toPeriod(); case Wo4W: return Weeks.weeks(4).toPeriod(); case WoW: default: return Weeks.ONE.toPeriod(); } }
public static String getRelativeDate(LocalDate today, LocalDate previousDate) { //These calculations are relatively expensive, so we'll only do the ones we absolutely need to int years = Years.yearsBetween(previousDate, today).getYears(); if (years > 1) { return years + " Years Ago"; } else if (years == 1) { return "One Year Ago"; } else { int months = Months.monthsBetween(previousDate, today).getMonths(); if (months > 1) { return months + " Months Ago"; } else if (months == 1) { return "1 Month Ago"; } else { int weeks = Weeks.weeksBetween(previousDate, today).getWeeks(); if (weeks > 1) { return weeks + " Weeks Ago"; } else if (weeks == 1) { return "1 Week Ago"; } else { int days = Days.daysBetween(previousDate, today).getDays(); if (days > 1) { return days + " Days Ago"; } else if (days == 1) { return "Yesterday"; } else { return "Previously"; } } } } }
public SortedSet<Integer> getWeeks(final Interval lessonInterval) { final SortedSet<Integer> weeks = new TreeSet<Integer>(); final LocalDate firstPossibleLessonDay = lessonInterval.getStart().toLocalDate(); for (final LocalDate localDate : dates) { final Integer week = Weeks.weeksBetween(firstPossibleLessonDay, localDate).getWeeks() + 1; weeks.add(week); } return weeks; }
public String getOccurrenceWeeksAsString() { final SortedSet<Integer> weeks = new TreeSet<Integer>(); final ExecutionCourse executionCourse = getExecutionCourse(); final YearMonthDay firstPossibleLessonDay = executionCourse.getMaxLessonsPeriod().getLeft(); final YearMonthDay lastPossibleLessonDay = executionCourse.getMaxLessonsPeriod().getRight(); for (final Interval interval : getAllLessonIntervals()) { final Integer week = Weeks.weeksBetween(firstPossibleLessonDay, interval.getStart().toLocalDate()).getWeeks() + 1; weeks.add(week); } final StringBuilder builder = new StringBuilder(); final Integer[] weeksA = weeks.toArray(new Integer[0]); for (int i = 0; i < weeksA.length; i++) { if (i == 0) { builder.append(weeksA[i]); } else if (i == weeksA.length - 1 || (weeksA[i]) + 1 != (weeksA[i + 1])) { final String seperator = (weeksA[i - 1]) + 1 == (weeksA[i]) ? " - " : ", "; builder.append(seperator); builder.append(weeksA[i]); } else if ((weeksA[i - 1]) + 1 != weeksA[i]) { builder.append(", "); builder.append(weeksA[i]); } } return builder.toString(); }
/** * return number of weeks since Jan 5, 1970 * * @param v date to calculate week number off of * @return number of weeks */ static public int getWeekNumber(DateTime v) { DateTime root = new DateTime(1970, 1, 5, 0, 0, 0, 0, v.getZone()); // use the same zone return Weeks.weeksBetween(root, v).getWeeks(); //long n = v.getMillis() - 345600000; // start of first week //return (int) (n / 604800000); }
public static String getRelativeDate(LocalDate today, LocalDate previousDate) { //These calculations are relatively expensive, so we'll only do the ones we absolutely need to int years = Years.yearsBetween(previousDate, today).getYears(); if (years > 1) { return years + " Years Ago"; } else if (years == 1) { return "One Year Ago"; } else { int months = Months.monthsBetween(previousDate, today).getMonths(); if (months > 1) { return months + " Months Ago"; } else if (months == 1) { return "1 Month Ago"; } else { int weeks = Weeks.weeksBetween(previousDate, today).getWeeks(); if (weeks > 1) { return weeks + " Weeks Ago"; } else if (weeks == 1) { return "1 Week Ago"; } else { int days = Days.daysBetween(previousDate, today).getDays(); if (days > 1) { return days + " Days Ago"; } else if (days == 1) { return "Yesterday"; } else { return "Today"; } } } } }
@Override public void setValue(Object value) { if (value == null || value instanceof Weeks) { super.setValue(value); } else if (value instanceof Number) { super.setValue(Weeks.weeks(abs(((Number) value).intValue()))); } else { throw new IllegalArgumentException("Invalid value " + value); } }
private boolean matchesSchedule(Calendar firstDate, Calendar testDate) { DateMidnight dmFirst = new DateMidnight(firstDate.getTimeInMillis()); DateMidnight dmTest = new DateMidnight(testDate.getTimeInMillis()); Weeks weeks = Weeks.weeksBetween(dmFirst, dmTest); if (0 != weeks.getWeeks() % frequency) { return false; } int dow = testDate.get(Calendar.DAY_OF_WEEK); int dayIndex = ((dow - Calendar.SUNDAY) + 6) % 7; return occurrs[dayIndex]; }
/** * Return string describing the time until/elapsed time since 'time' formatted like * "[relative time/date], [time]". * * See {@link android.text.format.DateUtils#getRelativeDateTimeString} for full docs. * * @param context the context * @param time some time * @param transitionResolution the elapsed time (period) at which * to stop reporting relative measurements. Periods greater * than this resolution will default to normal date formatting. * For example, will transition from "6 days ago" to "Dec 12" * when using Weeks.ONE. If null, defaults to Days.ONE. * Clamps to min value of Days.ONE, max of Weeks.ONE. * @param flags flags for getRelativeTimeSpanString() (if duration is less than transitionResolution) */ public static CharSequence getRelativeDateTimeString(Context context, ReadableInstant time, ReadablePeriod transitionResolution, int flags) { Resources r = context.getResources(); // We set the millis to 0 so we aren't off by a fraction of a second when counting duration DateTime now = DateTime.now(time.getZone()).withMillisOfSecond(0); DateTime timeDt = new DateTime(time).withMillisOfSecond(0); boolean past = !now.isBefore(timeDt); Duration duration = past ? new Duration(timeDt, now) : new Duration(now, timeDt); // getRelativeTimeSpanString() doesn't correctly format relative dates // above a week or exact dates below a day, so clamp // transitionResolution as needed. Duration transitionDuration; Duration minDuration = Days.ONE.toPeriod().toDurationTo(timeDt); if (transitionResolution == null) { transitionDuration = minDuration; } else { transitionDuration = past ? transitionResolution.toPeriod().toDurationTo(now) : transitionResolution.toPeriod().toDurationFrom(now); Duration maxDuration = Weeks.ONE.toPeriod().toDurationTo(timeDt); if (transitionDuration.isLongerThan(maxDuration)) { transitionDuration = maxDuration; } else if (transitionDuration.isShorterThan(minDuration)) { transitionDuration = minDuration; } } CharSequence timeClause = formatDateRange(context, time, time, FORMAT_SHOW_TIME); String result; if (!duration.isLongerThan(transitionDuration)) { CharSequence relativeClause = getRelativeTimeSpanString(context, time, flags); result = r.getString(R.string.joda_time_android_relative_time, relativeClause, timeClause); } else { CharSequence dateClause = getRelativeTimeSpanString(context, time, false); result = r.getString(R.string.joda_time_android_date_time, dateClause, timeClause); } return result; }
public static int weeksBetween(Date start, Date end) { DateTime startDateTime = new DateTime(start); DateTime endDateTime = new DateTime(end); return Weeks.weeksBetween(startDateTime, endDateTime).getWeeks(); }
/** * Set set date of the selected week * * @param calendar */ public void setDateWeek(Calendar calendar) { LocalDateTime ldt = LocalDateTime.fromCalendarFields(calendar); AppController.getInstance().setSelected(ldt); int nextPage = Weeks.weeksBetween(mStartDate, ldt).getWeeks(); if (nextPage >= 0 && nextPage < getWeekBetweenDates(start, end)) { pager.setCurrentItem(nextPage); calenderListener.onSelectDate(ldt); WeekFragment fragment = (WeekFragment) pager.getAdapter().instantiateItem(pager, nextPage); fragment.ChangeSelector(ldt); } }
public int getWeekBetweenDates(DateTime start, DateTime end) { int diff = Weeks.weeksBetween(start, end).getWeeks(); diff = diff + 1; return diff; }
@Transactional(readOnly = false) @SuppressWarnings("unchecked") public void sendEmailReminders() { try { int currentDayOfWeek = new DateTime().getDayOfWeek(); int currentDayOfMonth = new DateTime().getDayOfMonth(); DateTime todayDateTime = new DateTime(); for (SurveyDefinition surveyDefinition : surveyDefinitionDAO.findAllInternal()){ if (surveyDefinition.getSendAutoReminders()&& surveyDefinition.getUsers().size()>0 && surveyDefinition.getStatusAsString().equals("P")) { Date lastSentDate = surveyDefinition.getAutoReminderLastSentDate(); switch (surveyDefinition.getAutoRemindersFrequency()) { case WEEKLY: int weeks; if (lastSentDate !=null) {weeks = Weeks.weeksBetween(new DateTime(lastSentDate),todayDateTime).getWeeks(); } else {weeks = 1000;} if (weeks >= surveyDefinition.getAutoRemindersWeeklyOccurrence()) { for (Day day : surveyDefinition.getAutoRemindersDays()) { if (day.getId().equals(new Long(currentDayOfWeek))) { sendEmailReminder(surveyDefinition); } } } break; case MONTHLY: int months; if (lastSentDate !=null) {months = Months.monthsBetween(new DateTime(lastSentDate), todayDateTime).getMonths(); } else {months = 1000;} if (months>=surveyDefinition.getAutoRemindersMonthlyOccurrence() && surveyDefinition.getAutoRemindersDayOfMonth().equals(currentDayOfMonth)) { sendEmailReminder(surveyDefinition); } break; } } } } catch (RuntimeException e) { log.error(e.getMessage(),e); } }
@Test public void creates_instance_of_Weeks() { Weeks weeks = fixture.create(Weeks.class); assertThat(weeks, notNullValue()); assertThat(weeks, is(Weeks.weeks(52))); }
@Test public void testCustom() { long inputs[] = new long[NUM_ROWS]; long expectedWeeks[] = new long[NUM_ROWS]; long expectedMonths[] = new long[NUM_ROWS]; long expectedYears[] = new long[NUM_ROWS]; long seed = System.nanoTime(); Random random = new Random(seed); MutableDateTime dateTime = new MutableDateTime(0L, DateTimeZone.UTC); for (int i = 0; i < NUM_ROWS; i++) { inputs[i] = Math.abs(random.nextLong() % System.currentTimeMillis()); dateTime.setDate(inputs[i]); expectedWeeks[i] = Weeks.weeksBetween(EPOCH_START_DATE, dateTime).getWeeks(); expectedMonths[i] = Months.monthsBetween(EPOCH_START_DATE, dateTime).getMonths(); expectedYears[i] = Years.yearsBetween(EPOCH_START_DATE, dateTime).getYears(); } // Test for WEEKS conversion. long output[] = new long[NUM_ROWS]; TimeUnitConverter weekConverter = TimeConverterFactory.getTimeConverter("wEeKs"); weekConverter.convert(inputs, TimeUnit.MILLISECONDS, NUM_ROWS, output); for (int i = 0; i < NUM_ROWS; i++) { Assert.assertEquals(output[i], expectedWeeks[i]); } // Test for MONTHS conversion. TimeUnitConverter monthConverter = TimeConverterFactory.getTimeConverter("mOnThS"); monthConverter.convert(inputs, TimeUnit.MILLISECONDS, NUM_ROWS, output); for (int i = 0; i < NUM_ROWS; i++) { Assert.assertEquals(output[i], expectedMonths[i]); } // Test for YEARS conversion. TimeUnitConverter yearConverter = TimeConverterFactory.getTimeConverter("yEaRs"); yearConverter.convert(inputs, TimeUnit.MILLISECONDS, NUM_ROWS, output); for (int i = 0; i < NUM_ROWS; i++) { Assert.assertEquals(output[i], expectedYears[i]); } }
public void updateSchedules(Reportal report, ScheduleManager scheduleManager, User user, Flow flow) throws ScheduleManagerException { // Clear previous schedules removeSchedules(scheduleManager); // Add new schedule if (schedule) { int hour = (Integer.parseInt(scheduleHour) % 12) + (scheduleAmPm.equalsIgnoreCase("pm") ? 12 : 0); int minute = Integer.parseInt(scheduleMinute) % 60; DateTimeZone timeZone = scheduleTimeZone.equalsIgnoreCase("UTC") ? DateTimeZone.UTC : DateTimeZone.getDefault(); DateTime firstSchedTime = DateTimeFormat.forPattern("MM/dd/yyyy").withZone(timeZone) .parseDateTime(scheduleDate); firstSchedTime = firstSchedTime.withHourOfDay(hour).withMinuteOfHour(minute) .withSecondOfMinute(0).withMillisOfSecond(0); ReadablePeriod period = null; if (scheduleRepeat) { int intervalQuantity = Integer.parseInt(scheduleIntervalQuantity); if (scheduleInterval.equals("y")) { period = Years.years(intervalQuantity); } else if (scheduleInterval.equals("m")) { period = Months.months(intervalQuantity); } else if (scheduleInterval.equals("w")) { period = Weeks.weeks(intervalQuantity); } else if (scheduleInterval.equals("d")) { period = Days.days(intervalQuantity); } else if (scheduleInterval.equals("h")) { period = Hours.hours(intervalQuantity); } else if (scheduleInterval.equals("M")) { period = Minutes.minutes(intervalQuantity); } } ExecutionOptions options = new ExecutionOptions(); options.getFlowParameters().put("reportal.execution.user", user.getUserId()); options.getFlowParameters().put("reportal.title", report.title); options.getFlowParameters().put("reportal.render.results.as.html", report.renderResultsAsHtml ? "true" : "false"); options.setMailCreator(ReportalMailCreator.REPORTAL_MAIL_CREATOR); long endScheduleTime = report.endSchedule == null ? DEFAULT_SCHEDULE_END_EPOCH_TIME: parseDateToEpoch(report.endSchedule); logger.info("This report scheudle end time is " + endScheduleTime); scheduleManager.scheduleFlow(-1, project.getId(), project.getName(), flow.getId(), "ready", firstSchedTime.getMillis(), endScheduleTime, firstSchedTime.getZone(), period, DateTime.now().getMillis(), firstSchedTime.getMillis(), firstSchedTime.getMillis(), user.getUserId(), options, null); } }
public WeeksValue(Weeks arg) { setValue(arg); }