/** * Randomized test on TimeUnitRounding. Test uses random * {@link DateTimeUnit} and {@link DateTimeZone} and often (50% of the time) * chooses test dates that are exactly on or close to offset changes (e.g. * DST) in the chosen time zone. * * It rounds the test date down and up and performs various checks on the * rounding unit interval that is defined by this. Assumptions tested are * described in * {@link #assertInterval(long, long, long, Rounding, DateTimeZone)} */ public void testRoundingRandom() { for (int i = 0; i < 1000; ++i) { DateTimeUnit timeUnit = randomTimeUnit(); DateTimeZone tz = randomDateTimeZone(); Rounding rounding = new Rounding.TimeUnitRounding(timeUnit, tz); long date = Math.abs(randomLong() % (2 * (long) 10e11)); // 1970-01-01T00:00:00Z - 2033-05-18T05:33:20.000+02:00 long unitMillis = timeUnit.field(tz).getDurationField().getUnitMillis(); if (randomBoolean()) { nastyDate(date, tz, unitMillis); } final long roundedDate = rounding.round(date); final long nextRoundingValue = rounding.nextRoundingValue(roundedDate); assertInterval(roundedDate, date, nextRoundingValue, rounding, tz); // check correct unit interval width for units smaller than a day, they should be fixed size except for transitions if (unitMillis <= DateTimeConstants.MILLIS_PER_DAY) { // if the interval defined didn't cross timezone offset transition, it should cover unitMillis width if (tz.getOffset(roundedDate - 1) == tz.getOffset(nextRoundingValue + 1)) { assertThat("unit interval width not as expected for [" + timeUnit + "], [" + tz + "] at " + new DateTime(roundedDate), nextRoundingValue - roundedDate, equalTo(unitMillis)); } } } }
public static CalendarWeek getWeekIncludeThisDay(LocalDate localDate) { LocalDate monday = localDate.withDayOfWeek(DateTimeConstants.MONDAY); LocalDate tuesday = localDate.withDayOfWeek(DateTimeConstants.TUESDAY); LocalDate wednesday = localDate.withDayOfWeek(DateTimeConstants.WEDNESDAY); LocalDate thursday = localDate.withDayOfWeek(DateTimeConstants.THURSDAY); LocalDate friday = localDate.withDayOfWeek(DateTimeConstants.FRIDAY); LocalDate saturday = localDate.withDayOfWeek(DateTimeConstants.SATURDAY); LocalDate sunday = localDate.withDayOfWeek(DateTimeConstants.SUNDAY); CalendarWeek calendarWeek = new CalendarWeek( monday, tuesday, wednesday, thursday, friday, saturday, sunday ); calendarWeek.firstDayOfCurrentMonth = localDate.withDayOfMonth(1); calendarWeek.originDate = localDate; return calendarWeek; }
public static long getDayOfWeekTimeFlag(int dayOfWeek) { dayOfWeek = (dayOfWeek - 1) % 7 + 1; switch (dayOfWeek) { case DateTimeConstants.SUNDAY: return FLAG_SUNDAY; case DateTimeConstants.MONDAY: return FLAG_MONDAY; case DateTimeConstants.SATURDAY: return FLAG_SATURDAY; case DateTimeConstants.WEDNESDAY: return FLAG_WEDNESDAY; case DateTimeConstants.TUESDAY: return FLAG_TUESDAY; case DateTimeConstants.THURSDAY: return FLAG_THURSDAY; case DateTimeConstants.FRIDAY: return FLAG_FRIDAY; } throw new IllegalArgumentException("dayOfWeek = " + dayOfWeek); }
public static List<String> getMondaysFromCurrentSchoolYear(String dateFormat) { LocalDate startDate = new LocalDate(getCurrentSchoolYear(), 9, 1); LocalDate endDate = new LocalDate(getCurrentSchoolYear() + 1, 8, 31); List<String> dateList = new ArrayList<>(); LocalDate thisMonday = startDate.withDayOfWeek(DateTimeConstants.MONDAY); if (startDate.isAfter(thisMonday)) { startDate = thisMonday.plusWeeks(1); } else { startDate = thisMonday; } while (startDate.isBefore(endDate)) { dateList.add(startDate.toString(dateFormat)); startDate = startDate.plusWeeks(1); } return dateList; }
private String getDateOfCurrentMonday() { DateTime currentDate = new DateTime(); if (currentDate.getDayOfWeek() == DateTimeConstants.SATURDAY) { currentDate = currentDate.plusDays(2); } else if (currentDate.getDayOfWeek() == DateTimeConstants.SUNDAY) { currentDate = currentDate.plusDays(1); } else { currentDate = currentDate.withDayOfWeek(DateTimeConstants.MONDAY); } return currentDate.toString(DATE_PATTERN); }
/** * Generates the datetime bounds for the last N weeks, this week inclusive * The first day of the week is considered to be a Monday (1) * @param dateTime the anchor date * @param nPastWeeks the number of weeks to compute * @return a series of n week objects, containing the start date and end date of those weeks */ public static ArrayList<Week> GetNPastWeeks(DateTime dateTime, int nPastWeeks) { if (nPastWeeks < 1) return new ArrayList<>(); LocalDate localDate = new LocalDate(dateTime); DateTime monday = localDate.withDayOfWeek(DateTimeConstants.MONDAY) .toDateTimeAtStartOfDay(); DateTime sunday = localDate.withDayOfWeek(DateTimeConstants.SUNDAY) .toDateTimeAtStartOfDay().plusDays(1) .minusMillis(1); Week datePair = new Week(monday, sunday); ArrayList<Week> datePairs = new ArrayList<>(nPastWeeks); datePairs.add(datePair); for (int i = 1; i < nPastWeeks; ++i) { datePairs.add(new Week( datePairs.get(i - 1).getStartOfWeek().minusWeeks(1), datePairs.get(i - 1).getEndOfWeek().minusWeeks(1))); } Collections.reverse(datePairs); return datePairs; }
/** * Convert a habit to its data model * @param habit the habit to convert */ public HabitDataModel(Habit habit) { key = habit.getKey(); userId = habit.getUserId(); title = habit.getTitle(); reason = habit.getReason(); startDate = habit.getStartDate().getMillis(); schedule = new ArrayList<>(DateTimeConstants.DAYS_PER_WEEK); for (int i = 0; i < DateTimeConstants.DAYS_PER_WEEK; i++) { schedule.add(habit.getSchedule().contains(i + 1)); } completionRate = habit.getCompletionRate(); }
/** * Convert to a habit * @return the corresponding Habit object */ @Exclude public Habit getHabit() { HashSet<Integer> newSchedule = new HashSet<>(DateTimeConstants.DAYS_PER_WEEK); for(int i = 0; i < schedule.size(); i++) { if(schedule.get(i)) { newSchedule.add(i + 1); } } Habit habit = new Habit(); habit.setKey(key); habit.setUserId(userId); habit.setTitle(title); habit.setReason(reason); habit.setStartDate(new DateTime(startDate)); habit.setSchedule(newSchedule); habit.setCompletionRate(completionRate); if (completionRate != null) { habit.setStatus(HabitStatus.fromCompletionRate(completionRate)); } return habit; }
public void testGetMillisKeepLocal() { long millisLondon = TEST_TIME_SUMMER; long millisParis = TEST_TIME_SUMMER - 1L * DateTimeConstants.MILLIS_PER_HOUR; assertEquals(millisLondon, LONDON.getMillisKeepLocal(LONDON, millisLondon)); assertEquals(millisParis, LONDON.getMillisKeepLocal(LONDON, millisParis)); assertEquals(millisLondon, PARIS.getMillisKeepLocal(PARIS, millisLondon)); assertEquals(millisParis, PARIS.getMillisKeepLocal(PARIS, millisParis)); assertEquals(millisParis, LONDON.getMillisKeepLocal(PARIS, millisLondon)); assertEquals(millisLondon, PARIS.getMillisKeepLocal(LONDON, millisParis)); DateTimeZone zone = DateTimeZone.getDefault(); try { DateTimeZone.setDefault(LONDON); assertEquals(millisLondon, PARIS.getMillisKeepLocal(null, millisParis)); } finally { DateTimeZone.setDefault(zone); } }
private Timetable createLessonsForWeek(LocalDate weekStart) { Timetable result = new Timetable(); for (int dayNo = DateTimeConstants.MONDAY; dayNo <= DateTimeConstants.FRIDAY; dayNo++) { List<List<JsonLesson>> schoolDay = new ArrayList<>(); for (int lessonNo = 0; lessonNo < repository.getList(PlainLesson.class).size(); lessonNo++) { ImmutableJsonLesson lesson = templates.jsonLesson() .withDayNo(dayNo); schoolDay.add(withLessonNumber(lesson, lessonNo)); } result.put(weekStart.plusDays(dayNo - 1), schoolDay); } //weekend result.put(weekStart.plusDays(5), newArrayList()); result.put(weekStart.plusDays(6), newArrayList()); result.get(weekStart).add(withLessonNumber(cancelledLesson(), 7)); result.get(weekStart.plusDays(1)).add(withLessonNumber(substitutionLesson(), 7)); //Empty lesson result.get(weekStart.plusDays(2)).remove(2); return result; }
@Override public void bindViewHolder(FlexibleAdapter adapter, ViewHolder holder, int position, List payloads) { this.backgroundView = holder.background; this.title = holder.announcementSubject; holder.announcementSubject.setText(announcement.subject()); ViewCompat.setTransitionName(holder.background, "announcement_background_" + announcement.id()); LibrusUtils.setTextViewValue(holder.announcementTeacherName, announcement.addedByName()); holder.announcementContent.setText(announcement.content()); Reader reader = new Reader(holder.itemView.getContext()); if (!reader.isRead(announcement)) holder.announcementSubject.setTypeface(holder.announcementSubject.getTypeface(), Typeface.BOLD); else holder.announcementSubject.setTypeface(null, Typeface.NORMAL); if (announcement.startDate().isBefore(LocalDate.now().withDayOfWeek(DateTimeConstants.MONDAY))) holder.announcementDate.setText(announcement.startDate().toString("d MMM.")); else holder.announcementDate.setText(announcement.startDate().dayOfWeek().getAsShortText(new Locale("pl"))); }
/** * @param d2 * @param d1 * @return the difference d2-d1 in minutes */ public static long getDateTimeDifferenceInMinutes(DateTime d2, DateTime d1) { if(d2.toLocalDate().isEqual(d1.toLocalDate())) { return d2.getMinuteOfDay() - d1.getMinuteOfDay(); } else { int minutesFromD1ToNextDay = DateTimeConstants.MINUTES_PER_DAY - d1.getMinuteOfDay(); int minutesFromD2ToPreviousDay = d2.getMinuteOfDay(); DateTime dayAfterD1 = endOfDay(d1).plusMillis(1); DateTime dayBeforeD2 = startOfDay(d2); int daysDifference = dayBeforeD2.getDayOfYear() - dayAfterD1.getDayOfYear() + (dayBeforeD2.getYear() - dayAfterD1.getYear()) * 365; return minutesFromD1ToNextDay + minutesFromD2ToPreviousDay + daysDifference * DateTimeConstants.MINUTES_PER_DAY; } }
private static int millisPerUnit(String unit) { switch (Ascii.toLowerCase(unit)) { case "d": return DateTimeConstants.MILLIS_PER_DAY; case "h": return DateTimeConstants.MILLIS_PER_HOUR; case "m": return DateTimeConstants.MILLIS_PER_MINUTE; case "s": return DateTimeConstants.MILLIS_PER_SECOND; case "ms": return 1; default: throw new IllegalArgumentException("Unknown duration unit " + unit); } }
@Test public void testCreatePeriod() { DateTime testDate = new DateTime( 2009, 4, 27, 0, 0 ); WeeklyPeriodType wpt = new WeeklyPeriodType(); Period p = wpt.createPeriod( testDate.toDate() ); DateTime startDate = new DateTime( 2009, 4, 27, 0, 0 ); DateTime endDate = new DateTime( 2009, 5, 3, 0, 0 ); assertFalse( "start date after given date", startDate.isAfter( p.getStartDate().getTime() ) ); assertFalse( "end date before given date", endDate.isAfter( p.getEndDate().getTime() ) ); assertTrue( startDate.getDayOfWeek() == DateTimeConstants.MONDAY ); assertTrue( endDate.getDayOfWeek() == DateTimeConstants.SUNDAY ); }
@Scheduled(fixedRate=DateTimeConstants.MILLIS_PER_DAY) public void run() { LocalDateTime lastImport = service.getLastImportDate(PublicationSource.ARXIV); for (String feedKey : FEEDS) { SyndFeedInput input = new SyndFeedInput(); try { SyndFeed feed = input.build(new XmlReader(new URL(ROOT_RSS_URL + feedKey))); List<String> ids = new ArrayList<String>(feed.getEntries().size()); for (SyndEntry entry : feed.getEntries()) { ids.add(entry.getLink().replace(URI_PREFIX, "")); } URL url = new URL("http://export.arxiv.org/api/query?id_list=" + joiner.join(ids) + "&max_results=100"); try (InputStream inputStream = url.openStream()) { List<Publication> publications = extractPublications(inputStream, lastImport, ids.size()); publications = publications.stream().filter(p -> p.getCreated().isAfter(lastImport)).collect(Collectors.toList()); logger.info("Obtained publications from arxiv for category {}: {}", feedKey, publications.size()); service.storePublication(publications); } } catch (IllegalArgumentException | FeedException | IOException e) { logger.error("Problem getting arxiv RSS feed", e); } } }
private boolean isMarketOpen(DateTime dateTime) { checkNotNull(dateTime); checkNotNullOrEmpty(forexCloseTime); checkNotNullOrEmpty(forexOpenTime); int dayOfWeek = dateTime.dayOfWeek().get(); switch (dayOfWeek) { case DateTimeConstants.SATURDAY: return false; case DateTimeConstants.FRIDAY: DateTime marketCloseTime = DateTime.parse(forexCloseTime, DATE_TIME_FORMATTER) .plus(dateTime.withTimeAtStartOfDay().getMillis()); return dateTime.compareTo(marketCloseTime) < 0; case DateTimeConstants.SUNDAY: DateTime marketOpenTime = DateTime.parse(forexOpenTime, DATE_TIME_FORMATTER) .plus(dateTime.withTimeAtStartOfDay().getMillis()); return dateTime.compareTo(marketOpenTime) >= 0; case DateTimeConstants.MONDAY: case DateTimeConstants.TUESDAY: case DateTimeConstants.WEDNESDAY: case DateTimeConstants.THURSDAY: return true; default: throw new IllegalArgumentException( String.format("Unsupported day of the week [%d]", dayOfWeek)); } }
long calculateFirstDayOfYearMillis(int year) { // Java epoch is 1970-01-01 Gregorian which is 1969-12-19 Julian. // Calculate relative to the nearest leap year and account for the // difference later. int relativeYear = year - 1968; int leapYears; if (relativeYear <= 0) { // Add 3 before shifting right since /4 and >>2 behave differently // on negative numbers. leapYears = (relativeYear + 3) >> 2; } else { leapYears = relativeYear >> 2; // For post 1968 an adjustment is needed as jan1st is before leap day if (!isLeapYear(year)) { leapYears++; } } long millis = (relativeYear * 365L + leapYears) * (long)DateTimeConstants.MILLIS_PER_DAY; // Adjust to account for difference between 1968-01-01 and 1969-12-19. return millis - (366L + 352) * DateTimeConstants.MILLIS_PER_DAY; }
long calculateFirstDayOfYearMillis(int year) { // Java epoch is 1970-01-01 Gregorian which is 1686-04-23 Coptic. // Calculate relative to the nearest leap year and account for the // difference later. int relativeYear = year - 1687; int leapYears; if (relativeYear <= 0) { // Add 3 before shifting right since /4 and >>2 behave differently // on negative numbers. leapYears = (relativeYear + 3) >> 2; } else { leapYears = relativeYear >> 2; // For post 1687 an adjustment is needed as jan1st is before leap day if (!isLeapYear(year)) { leapYears++; } } long millis = (relativeYear * 365L + leapYears) * (long)DateTimeConstants.MILLIS_PER_DAY; // Adjust to account for difference between 1687-01-01 and 1686-04-23. return millis + (365L - 112) * DateTimeConstants.MILLIS_PER_DAY; }
public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { if (minuendInstant < subtrahendInstant) { return -getDifference(subtrahendInstant, minuendInstant); } int minuendWeekyear = get(minuendInstant); int subtrahendWeekyear = get(subtrahendInstant); long minuendRem = remainder(minuendInstant); long subtrahendRem = remainder(subtrahendInstant); // Balance leap weekyear differences on remainders. if (subtrahendRem >= WEEK_53 && iChronology.getWeeksInYear(minuendWeekyear) <= 52) { subtrahendRem -= DateTimeConstants.MILLIS_PER_WEEK; } int difference = minuendWeekyear - subtrahendWeekyear; if (minuendRem < subtrahendRem) { difference--; } return difference; }
public long getDateTimeMillis( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } FieldUtils.verifyValueBounds(DateTimeFieldType.hourOfDay(), hourOfDay, 0, 23); FieldUtils.verifyValueBounds(DateTimeFieldType.minuteOfHour(), minuteOfHour, 0, 59); FieldUtils.verifyValueBounds(DateTimeFieldType.secondOfMinute(), secondOfMinute, 0, 59); FieldUtils.verifyValueBounds(DateTimeFieldType.millisOfSecond(), millisOfSecond, 0, 999); return getDateMidnightMillis(year, monthOfYear, dayOfMonth) + hourOfDay * DateTimeConstants.MILLIS_PER_HOUR + minuteOfHour * DateTimeConstants.MILLIS_PER_MINUTE + secondOfMinute * DateTimeConstants.MILLIS_PER_SECOND + millisOfSecond; }
/** * @param instant millis from 1970-01-01T00:00:00Z */ int getDayOfWeek(long instant) { // 1970-01-01 is day of week 4, Thursday. long daysSince19700101; if (instant >= 0) { daysSince19700101 = instant / DateTimeConstants.MILLIS_PER_DAY; } else { daysSince19700101 = (instant - (DateTimeConstants.MILLIS_PER_DAY - 1)) / DateTimeConstants.MILLIS_PER_DAY; if (daysSince19700101 < -3) { return 7 + (int) ((daysSince19700101 + 4) % 7); } } return 1 + (int) ((daysSince19700101 + 3) % 7); }
long getYearDifference(long minuendInstant, long subtrahendInstant) { int minuendYear = getYear(minuendInstant); int subtrahendYear = getYear(subtrahendInstant); // Inlined remainder method to avoid duplicate calls to get. long minuendRem = minuendInstant - getYearMillis(minuendYear); long subtrahendRem = subtrahendInstant - getYearMillis(subtrahendYear); // Balance leap year differences on remainders. if (subtrahendRem >= FEB_29) { if (isLeapYear(subtrahendYear)) { if (!isLeapYear(minuendYear)) { subtrahendRem -= DateTimeConstants.MILLIS_PER_DAY; } } else if (minuendRem >= FEB_29 && isLeapYear(minuendYear)) { minuendRem -= DateTimeConstants.MILLIS_PER_DAY; } } int difference = minuendYear - subtrahendYear; if (minuendRem < subtrahendRem) { difference--; } return difference; }
long calculateFirstDayOfYearMillis(int year) { // Java epoch is 1970-01-01 Gregorian which is 1962-04-23 Ethiopic. // Calculate relative to the nearest leap year and account for the // difference later. int relativeYear = year - 1963; int leapYears; if (relativeYear <= 0) { // Add 3 before shifting right since /4 and >>2 behave differently // on negative numbers. leapYears = (relativeYear + 3) >> 2; } else { leapYears = relativeYear >> 2; // For post 1963 an adjustment is needed as jan1st is before leap day if (!isLeapYear(year)) { leapYears++; } } long millis = (relativeYear * 365L + leapYears) * (long)DateTimeConstants.MILLIS_PER_DAY; // Adjust to account for difference between 1963-01-01 and 1962-04-23. return millis + (365L - 112) * DateTimeConstants.MILLIS_PER_DAY; }
long calculateFirstDayOfYearMillis(int year) { // Initial value is just temporary. int leapYears = year / 100; if (year < 0) { // Add 3 before shifting right since /4 and >>2 behave differently // on negative numbers. When the expression is written as // (year / 4) - (year / 100) + (year / 400), // it works for both positive and negative values, except this optimization // eliminates two divisions. leapYears = ((year + 3) >> 2) - leapYears + ((leapYears + 3) >> 2) - 1; } else { leapYears = (year >> 2) - leapYears + (leapYears >> 2); if (isLeapYear(year)) { leapYears--; } } return (year * 365L + (leapYears - DAYS_0000_TO_1970)) * DateTimeConstants.MILLIS_PER_DAY; }
@Test public void shouldReturnCurrentWeeksDatesFromMonToSun() throws Exception { LocalDate now = new LocalDate(); assertThat(now.withDayOfWeek(DateTimeConstants.MONDAY).toString(), is("2015-08-31")); assertThat(now.withDayOfWeek(DateTimeConstants.SUNDAY).toString(), is("2015-09-06")); ArrayList<String> currentWeeksDates = DateUtil.getCurrentWeeksDates(); assertThat(currentWeeksDates.size(), is(7)); assertThat(currentWeeksDates, hasItems( "31-08-2015", "01-09-2015", "02-09-2015", "03-09-2015", "04-09-2015", "05-09-2015", "06-09-2015") ); }
public static Collection<DateRange> splitAsDateRangeByWeek(LocalDate start, LocalDate end){ Set<DateRange> dates = new LinkedHashSet<DateRange>(); dates.add(new DateRange(start, start.withDayOfWeek(DateTimeConstants.SUNDAY))); LocalDate startDateOfWeek = start.withDayOfWeek(DateTimeConstants.MONDAY).plusWeeks(1); while(!startDateOfWeek.isAfter(end)){ LocalDate endDateOfWeek = startDateOfWeek.withDayOfWeek(DateTimeConstants.SUNDAY); if(endDateOfWeek.isAfter(end)){ endDateOfWeek = end; } dates.add(new DateRange(startDateOfWeek, endDateOfWeek)); startDateOfWeek = startDateOfWeek.plusWeeks(1); } return dates; }
private JsonNode toLeaderboard(List<HighScore> highScores) { highScores.sort(null); ObjectNode results = Json8.object(); ArrayNode today = results.putArray("today"); ArrayNode week = results.putArray("week"); ArrayNode forever = results.putArray("forever"); DateTime startOfDay = DateTime.now().withTimeAtStartOfDay(); DateTime startOfWeek = startOfDay.withDayOfWeek(DateTimeConstants.MONDAY); for (HighScore score : highScores) { if (score.date.isAfter(startOfDay)) { today.add(score.toNode()); week.add(score.toNode()); } else if (score.date.isAfter(startOfWeek)) week.add(score.toNode()); forever.add(score.toNode()); } return results; }
@Test public void shouldScheduleInterveningRepeatJob() throws SchedulerException { try { fakeNow(newDateTime(2020, 7, 15, 10, 0, 0)); Map<String, Object> params = new HashMap<>(); params.put(MotechSchedulerService.JOB_ID_KEY, "job_id"); schedulerService.scheduleRepeatingJob( new RepeatingSchedulableJob( new MotechEvent("test_event", params), DateTimeConstants.SECONDS_PER_DAY, newDateTime(2020, 7, 14, 12, 0, 0), newDateTime(2020, 7, 18, 12, 0, 0), true) ); List<DateTime> fireTimes = getFireTimes("test_event-job_id-repeat"); assertEquals(asList( newDateTime(2020, 7, 15, 12, 0, 0), newDateTime(2020, 7, 16, 12, 0, 0), newDateTime(2020, 7, 17, 12, 0, 0)), fireTimes); } finally { stopFakingTime(); } }
@Test public void shouldScheduleInterveningRepeatJobWithoutEndDate() throws SchedulerException { try { fakeNow(newDateTime(2020, 7, 15, 10, 0, 0)); Map<String, Object> params = new HashMap<>(); params.put(MotechSchedulerService.JOB_ID_KEY, "job_id"); RepeatingSchedulableJob repeatJob = new RepeatingSchedulableJob( new MotechEvent("test_event", params), 3, DateTimeConstants.SECONDS_PER_DAY, newDateTime(2020, 7, 13, 12, 0, 0), null, true); repeatJob.setUseOriginalFireTimeAfterMisfire(false); schedulerService.scheduleRepeatingJob(repeatJob); List<DateTime> fireTimes = getFireTimes("test_event-job_id-repeat"); assertEquals(asList( newDateTime(2020, 7, 15, 12, 0, 0), newDateTime(2020, 7, 16, 12, 0, 0)), fireTimes); } finally { stopFakingTime(); } }
private List<Message> getIncomingMessages(long lastMessageMillis, User user) { if (!isServiceEnabled(user)) { return Collections.emptyList(); } try { FacebookClient client = helper.getBackgroundFacebookClient(user); List<StreamPost> feed = client.executeFqlQuery(NEWS_FEED_QUERY + " AND created_time > " + (lastMessageMillis / DateTimeConstants.MILLIS_PER_SECOND + 1) + " LIMIT 20", StreamPost.class); List<Message> messages = helper.streamPostsToMessages(feed, user.getFacebookSettings().isFetchImages(), user.getFacebookSettings().getUserId(), client); return messages; } catch (FacebookException e) { //do nothing, will re-attempt on next run handleException("Problem retrieving incoming facebook messages", e, user); return Collections.emptyList(); } }
@Scheduled(fixedRate=DateTimeConstants.MILLIS_PER_MINUTE) @SqlTransactional public void shareScheduledMessages() { while (true) { if (queue.isEmpty()) { break; } DateTime messageTime = queue.peek().getScheduledTime(); // send messages whose time is before the current moment. This job runs every minute, // so the maximum delay for a message will be 1 minute if (messageTime.isBeforeNow()) { ScheduledMessage msg = queue.poll(); shareService.share(msg.getText(), msg.getUserId(), Arrays.asList(StringUtils.split(msg.getPictureUrls(), DELIMITER)), Arrays.asList(StringUtils.split(msg.getExternalSites(), DELIMITER)), Arrays.asList(StringUtils.split(msg.getHideFromUsernames(), DELIMITER)), msg.isHideFromCloseFriends()); shareService.delete(msg); } else { break; } } }
@Scheduled(fixedRate=2 * DateTimeConstants.MILLIS_PER_HOUR) public void importMessages() { userDao.performBatched(User.class, 100, new Dao.PageableOperation<User>() { @Override public void execute() { for (User user : getData()) { for (SocialNetworkService sns : socialNetworks) { try { sns.importMessages(user); // the method itself verifies whether the user has configured import } catch (Exception ex) { logger.error("Problem importing messages for user " + user, ex); } } } } }); }
/** * Gets all expirations for the current symbol and then excludes dates that are not part of the monthly expirations. * Dates are 15th - 22nd, if it's the 22nd, then the 22nd has to be a Sat * * There are some expirations on Friday and Sat where 1 of the 2 only has a few options available. * * @return monthly expirations */ public List<Date> getMonthlyExpirations() { List<Date> monthlyExpirations = new ArrayList<Date>(); List<Date> allExpirations = getExpirations(); for (Date date : allExpirations) { DateTime jDate = new DateTime(date); if (jDate.dayOfMonth().get() >= 15 && jDate.dayOfMonth().get() <= 22) { if ((jDate.dayOfMonth().get() == 22 && jDate.getDayOfWeek() != DateTimeConstants.SATURDAY) || jDate.getDayOfWeek() == DateTimeConstants.SUNDAY || jDate.getDayOfWeek() == DateTimeConstants.MONDAY || jDate.getDayOfWeek() == DateTimeConstants.TUESDAY || jDate.getDayOfWeek() == DateTimeConstants.WEDNESDAY || jDate.getDayOfWeek() == DateTimeConstants.THURSDAY ) { // skip } else { //System.out.println(jDate.toString() + " - " + jDate.getDayOfWeek()); monthlyExpirations.add(date); } } } return monthlyExpirations; }
private boolean getExpanded(String dayDate) { DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(DATE_PATTERN); DateTime dayTime = dateTimeFormatter.parseDateTime(dayDate); DateTime currentDate = new DateTime(); if (currentDate.getDayOfWeek() == DateTimeConstants.SATURDAY) { currentDate = currentDate.plusDays(2); } else if (currentDate.getDayOfWeek() == DateTimeConstants.SUNDAY) { currentDate = currentDate.plusDays(1); } return DateTimeComparator.getDateOnlyInstance().compare(currentDate, dayTime) == 0; }
private Week getWeek() { if (date == null) { LocalDate currentMonday = new LocalDate().withDayOfWeek(DateTimeConstants.MONDAY); date = currentMonday.toString(DATE_PATTERN); } return getDaoSession().getWeekDao().queryBuilder() .where(WeekDao.Properties.StartDayDate.eq(date), WeekDao.Properties.UserId.eq(getUserId())) .unique(); }
@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(); }
/** * 计算当前是星期几 * 返回 星期x */ public static String getWeekday(Date date) { DateTime dt = new DateTime(date); String weekday = ""; //星期 switch(dt.getDayOfWeek()) { case DateTimeConstants.SUNDAY: weekday = "星期日"; break; case DateTimeConstants.MONDAY: weekday = "星期一"; break; case DateTimeConstants.TUESDAY: weekday = "星期二"; break; case DateTimeConstants.WEDNESDAY: weekday = "星期三"; break; case DateTimeConstants.THURSDAY: weekday = "星期四"; break; case DateTimeConstants.FRIDAY: weekday = "星期五"; break; case DateTimeConstants.SATURDAY: weekday = "星期六"; break; } return weekday; }
/** 返回 周x */ public static String getWeekday2(Date date) { DateTime dt = new DateTime(date); String weekday = ""; //星期 switch(dt.getDayOfWeek()) { case DateTimeConstants.SUNDAY: weekday = "周日"; break; case DateTimeConstants.MONDAY: weekday = "周一"; break; case DateTimeConstants.TUESDAY: weekday = "周二"; break; case DateTimeConstants.WEDNESDAY: weekday = "周三"; break; case DateTimeConstants.THURSDAY: weekday = "周四"; break; case DateTimeConstants.FRIDAY: weekday = "周五"; break; case DateTimeConstants.SATURDAY: weekday = "周六"; break; } return weekday; }