private static boolean keepCurrent(Calendar asOfDate) { boolean keepCurrent = false; int monthNow = asOfDate.get(Calendar.MONTH); // March, June, September, and December are expiration months boolean isExpirationMonth = ((monthNow + 1) % 3 == 0); if (isExpirationMonth) { Calendar volumeShiftDate = (Calendar) asOfDate.clone(); // Find first Friday volumeShiftDate.set(Calendar.DAY_OF_MONTH, 1); while (volumeShiftDate.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY) { volumeShiftDate.add(Calendar.DAY_OF_MONTH, 1); } // Shift to third Friday volumeShiftDate.add(Calendar.WEEK_OF_MONTH, 2); // Finally, find the day before second Friday volumeShiftDate.add(Calendar.DAY_OF_MONTH, -8); if (asOfDate.before(volumeShiftDate)) { keepCurrent = true; } } return keepCurrent; }
public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage : java CalendarEx7 2004 11"); return; } int year = Integer.parseInt(args[0]); int month = Integer.parseInt(args[1]); Calendar sDay = Calendar.getInstance(); // 시작일 Calendar eDay = Calendar.getInstance(); // 끝일 // 월의 경우 0부터 11까지의 값을 가지므로 1을 빼줘야 한다. // 예를 들어, 2004년 11월 1일은 sDay.set(2004,10,1);과 같이 해줘야 한다. sDay.set(year, month - 1, 1); // 입력월의 1일로 설정 한다. // 입력 월의 말일로 설정한다. eDay.set(year, month - 1, sDay.getActualMaximum(Calendar.DATE)); // 1일이 속한 주의일요일로 날짜설정. sDay.add(Calendar.DATE, -sDay.get(Calendar.DAY_OF_WEEK) + 1); // 말일이 속한 주의 토요일로 날짜설정 eDay.add(Calendar.DATE, 7 - eDay.get(Calendar.DAY_OF_WEEK)); System.out.println(" " + year + "년 " + month + "월"); System.out.println(" SU MO TU WE TH FR SA"); // 시작일과 마지막일까지(sDay<=eDay) 1일씩 증가시켜가면서 일(Calendar.DATE)을 출력한다. for (int n = 1; sDay.before(eDay) || sDay.equals(eDay); sDay.add(Calendar.DATE, 1)) { int day = sDay.get(Calendar.DATE); System.out.print((day < 10) ? " " + day : " " + day); if (n++ % 7 == 0) { System.out.println(); // 7일치를 찍고 나서 죽을 바꾼다. } } } // main
@Override public GwtRpcResponseList<WeekInterface> execute( WeekSelectorRequest command, SessionContext context) { GwtRpcResponseList<WeekInterface> ret = new GwtRpcResponseList<WeekInterface>(); Session session = SessionDAO.getInstance().get(command.getSessionId()); Calendar c = Calendar.getInstance(Locale.US); c.setTime(session.getEventBeginDate()); while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) { c.add(Calendar.DAY_OF_YEAR, -1); } int sessionYear = session.getSessionStartYear(); Formats.Format<Date> df = Formats.getDateFormat(Formats.Pattern.DATE_EVENT_SHORT); while (!c.getTime().after(session.getEventEndDate())) { int dayOfYear = c.get(Calendar.DAY_OF_YEAR); if (c.get(Calendar.YEAR) < sessionYear) { Calendar x = Calendar.getInstance(Locale.US); x.set(c.get(Calendar.YEAR), 11, 31, 0, 0, 0); dayOfYear -= x.get(Calendar.DAY_OF_YEAR); } else if (c.get(Calendar.YEAR) > sessionYear) { Calendar x = Calendar.getInstance(Locale.US); x.set(sessionYear, 11, 31, 0, 0, 0); dayOfYear += x.get(Calendar.DAY_OF_YEAR); } WeekInterface week = new WeekInterface(); week.setDayOfYear(dayOfYear); for (int i = 0; i < 7; i++) { week.addDayName( new DateInterface( df.format(c.getTime()), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH))); c.add(Calendar.DAY_OF_YEAR, 1); } ret.add(week); } return ret; }
public Offer createOffer( String offerName, OfferType offerType, OfferDiscountType discountType, double value, String customerRule, String orderRule, boolean stackable, boolean combinable, int priority) { Offer offer = offerDao.create(); offer.setName(offerName); offer.setStartDate(SystemTime.asDate()); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, -1); offer.setStartDate(calendar.getTime()); calendar.add(Calendar.DATE, 2); offer.setEndDate(calendar.getTime()); offer.setType(offerType); offer.setDiscountType(discountType); offer.setValue(BigDecimal.valueOf(value)); offer.setDeliveryType(OfferDeliveryType.CODE); offer.setStackable(stackable); offer.setAppliesToOrderRules(orderRule); offer.setAppliesToCustomerRules(customerRule); offer.setCombinableWithOtherOffers(combinable); offer.setPriority(priority); offer = offerService.save(offer); offer.setMaxUses(50); return offer; }
@Test public void checkBooking() throws CabNotAvailableException { Cab one = new Cab("DL01HB001", 100020); Cab two = new Cab("DL01HB002", 100040); Cab three = new Cab("DL01HB003", 100060); Cab four = new Cab("DL01HB004", 100080); ICabBookingSystem system = new CabBookingSystemImpl(); system.addCab(one); system.addCab(two); system.addCab(three); system.addCab(four); Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR_OF_DAY, 10); String cab = system.requestForCab(new CabRequest("BR001", 100025, 100056, cal.getTime())); Assert.assertEquals(cab, "DL01HB001"); cal = Calendar.getInstance(); cal.add(Calendar.HOUR_OF_DAY, 11); cab = system.requestForCab(new CabRequest("BR002", 100056, 100022, cal.getTime())); Assert.assertEquals(cab, "DL01HB003"); cal = Calendar.getInstance(); cal.add(Calendar.HOUR_OF_DAY, 15); cab = system.requestForCab(new CabRequest("BR003", 100020, 100075, cal.getTime())); Assert.assertEquals(cab, "DL01HB003"); cal = Calendar.getInstance(); cal.add(Calendar.HOUR_OF_DAY, 15); cab = system.requestForCab(new CabRequest("BR004", 100040, 100056, cal.getTime())); Assert.assertEquals(cab, "DL01HB002"); }
@Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_prev: fromCalendar.add(Calendar.MONTH, -1); toCalendar.add(Calendar.MONTH, -1); ((EditText) findViewById(R.id.from_date)).setText(Common.fmtDate(fromCalendar)); ((EditText) findViewById(R.id.to_date)).setText(Common.fmtDate(toCalendar)); mLoadType = LOAD_DAYS; loadNoteList(); break; case R.id.btn_next: fromCalendar.add(Calendar.MONTH, 1); toCalendar.add(Calendar.MONTH, 1); ((EditText) findViewById(R.id.from_date)).setText(Common.fmtDate(fromCalendar)); ((EditText) findViewById(R.id.to_date)).setText(Common.fmtDate(toCalendar)); mLoadType = LOAD_DAYS; loadNoteList(); break; case R.id.from_date: showDialog(NotesList.FROM_DATE_DIALOG_ID); break; case R.id.to_date: showDialog(NotesList.TO_DATE_DIALOG_ID); break; } }
public static java.util.Date addMonths(Comparable<?> param1, Comparable<?> param2, Calendar cal) throws ParseException { if (param1 == null && param2 == null) { return null; } try { int months = getInteger(param2); if (param1 instanceof Timestamp) { Timestamp d = (Timestamp) param1; cal.setTimeInMillis(d.getTime()); cal.add(Calendar.MONTH, months); return new Timestamp(cal.getTimeInMillis()); } else if (param1 instanceof java.sql.Date) { java.util.Date d = (java.util.Date) param1; cal.setTimeInMillis(d.getTime()); cal.add(Calendar.MONTH, months); return new java.util.Date(cal.getTimeInMillis()); } else { throw new ParseException(); } } catch (ParseException e) { throw new ParseException( WRONG_TYPE + " month_between(" + param1.getClass() + "," + param2.getClass() + ")"); } }
/** @see org.kuali.kfs.module.tem.document.TravelDocumentBase#initiateDocument() */ @Override public void initiateDocument() { super.initiateDocument(); // clear expenses setActualExpenses(new ArrayList<ActualExpense>()); setPerDiemExpenses(new ArrayList<PerDiemExpense>()); // default dates if null Calendar calendar = getDateTimeService().getCurrentCalendar(); if (getTripBegin() == null) { calendar.add(Calendar.DAY_OF_MONTH, 1); setTripBegin(new Timestamp(calendar.getTimeInMillis())); } if (getTripEnd() == null) { calendar.add(Calendar.DAY_OF_MONTH, 2); setTripEnd(new Timestamp(calendar.getTimeInMillis())); } // initiate payment and wire transfer this.travelPayment = new TravelPayment(); this.wireTransfer = new PaymentSourceWireTransfer(); // set due date to the next day calendar = getDateTimeService().getCurrentCalendar(); calendar.add(Calendar.DAY_OF_MONTH, 1); travelPayment.setDueDate(new java.sql.Date(calendar.getTimeInMillis())); travelPayment.setCheckStubText( getConfigurationService() .getPropertyValueAsString(TemKeyConstants.MESSAGE_TEM_REIMBURSEMENT_PAYMENT_HOLD_TEXT)); // set up the default bank setDefaultBankCode(); updatePayeeTypeForReimbursable(); }
private boolean setFocusToSelection() { if (dayPanel != null) { if (cdt.hasSelection()) { Calendar first = cdt.getCalendarInstance((Date) dayButtons[0].getData(CDT.Key.Date)); first.set(Calendar.MILLISECOND, 0); first.set(Calendar.SECOND, 0); first.set(Calendar.MINUTE, 0); first.set(Calendar.HOUR_OF_DAY, 0); Calendar last = cdt.getCalendarInstance((Date) dayButtons[dayButtons.length - 1].getData(CDT.Key.Date)); last.set(Calendar.MILLISECOND, 0); last.set(Calendar.SECOND, 0); last.set(Calendar.MINUTE, 0); last.set(Calendar.HOUR_OF_DAY, 0); last.add(Calendar.DATE, 1); last.add(Calendar.MILLISECOND, -1); Date selection = cdt.getSelection(); Calendar scal = cdt.getCalendarInstance(selection); for (int j = 0; j < dayButtons.length; j++) { Calendar tmpcal = cdt.getCalendarInstance((Date) dayButtons[j].getData(CDT.Key.Date)); if ((scal.get(Calendar.DATE) == tmpcal.get(Calendar.DATE)) && (scal.get(Calendar.MONTH) == tmpcal.get(Calendar.MONTH)) && (scal.get(Calendar.YEAR) == tmpcal.get(Calendar.YEAR))) { return dayButtons[j].setFocus(); } } } else { dayButtons[0].setFocus(); } } return true; }
private void refreshWeekBeforeSteps( DBHandler db, BarLineChartBase barChart, Calendar day, GBDevice device) { ActivityAnalysis analysis = new ActivityAnalysis(); day = (Calendar) day.clone(); // do not modify the caller's argument day.add(Calendar.DATE, -7); List<BarEntry> entries = new ArrayList<>(); List<String> labels = new ArrayList<>(); for (int counter = 0; counter < 7; counter++) { entries.add( new BarEntry(analysis.calculateTotalSteps(getSamplesOfDay(db, day, device)), counter)); labels.add(day.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, mLocale)); day.add(Calendar.DATE, 1); } BarDataSet set = new BarDataSet(entries, ""); set.setColor(akActivity.color); BarData data = new BarData(labels, set); data.setValueTextColor( Color .GRAY); // prevent tearing other graph elements with the black text. Another approach // would be to hide the values cmpletely with data.setDrawValues(false); LimitLine target = new LimitLine(mTargetSteps); barChart.getAxisLeft().getLimitLines().clear(); barChart.getAxisLeft().addLimitLine(target); setupLegend(barChart); barChart.setData(data); barChart.getLegend().setEnabled(false); }
public static Calendar computeNextAlarmTime( int hourOfDay, int minute, DaysOfWeek repeats, Calendar currentTime) { Calendar mustBeAfter = Calendar.getInstance(); mustBeAfter.setTimeInMillis(currentTime.getTimeInMillis()); mustBeAfter.add(Calendar.MINUTE, 1); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(currentTime.getTimeInMillis()); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); calendar.getTime(); // force internal recompute while (!calendar.after(mustBeAfter)) { calendar.add(Calendar.DAY_OF_WEEK, 1); // if alarm is only valid on certain days, keep incrementing till one of those days reached if (!repeats.isNoDaysSet()) { while (!repeats.isDaySet(calendar.get(Calendar.DAY_OF_WEEK))) { calendar.add(Calendar.DAY_OF_WEEK, 1); } } } return calendar; }
/** * 获取周的最后一天(SUNDAY) @Title: getLastDayOfWeek @Description: 偏移量指的是获取目标数与当前数的间隔,如想拿当前数,传入0 * * @param offset 偏移量 * @return Date 返回类型 */ public Date getLastDayOfWeek(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.DAY_OF_MONTH, offset * 7); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); cal.add(Calendar.DAY_OF_MONTH, 6); return cal.getTime(); }
/** * 获取旬的第一天 @Title: getFirstDayOfTendays @Description: 偏移量指的是获取目标数与当前数的间隔,如想拿当前数,传入0 * * @param offset 偏移量 * @return Date 返回类型 */ public Date getFirstDayOfTendays(int offset) { cal.setTime(this.fiducialDate); int day = cal.get(Calendar.DAY_OF_MONTH); if (day >= 21) { day = 21; } else if (day >= 11) { day = 11; } else { day = 1; } if (offset > 0) { day = day + 10 * offset; int monOffset = day / 30; day = day % 30; cal.add(Calendar.MONTH, monOffset); cal.set(Calendar.DAY_OF_MONTH, day); } else { int monOffset = 10 * offset / 30; int dayOffset = 10 * offset % 30; if ((day + dayOffset) > 0) { day = day + dayOffset; } else { monOffset = monOffset - 1; day = day - dayOffset - 10; } cal.add(Calendar.MONTH, monOffset); cal.set(Calendar.DAY_OF_MONTH, day); } return cal.getTime(); }
/** * 获取月的最后一天 @Title: getLastDayOfMonth @Description: 偏移量指的是获取目标数与当前数的间隔,如想拿当前数,传入0 * * @param offset 偏移量 * @return Date 返回类型 */ public Date getLastDayOfMonth(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.MONTH, offset + 1); cal.set(Calendar.DAY_OF_MONTH, 1); cal.add(Calendar.DAY_OF_MONTH, -1); return cal.getTime(); }
@Override protected Dialog onCreateDialog(int id) { // this method is called after invoking 'showDialog' for the first time // here we initiate the corresponding DateSlideSelector and return the dialog to its caller final Calendar c = Calendar.getInstance(); switch (id) { case DEFAULTDATESELECTOR_ID: return new DefaultDateSlider(this, mDateSetListener, c); case DEFAULTDATESELECTOR_WITHLIMIT_ID: final Calendar maxTime = Calendar.getInstance(); maxTime.add(Calendar.DAY_OF_MONTH, 14); return new DefaultDateSlider(this, mDateSetListener, c, c, maxTime); case ALTERNATIVEDATESELECTOR_ID: return new AlternativeDateSlider(this, mDateSetListener, c, c, null); case CUSTOMDATESELECTOR_ID: return new CustomDateSlider(this, mDateSetListener, c); case MONTHYEARDATESELECTOR_ID: return new MonthYearDateSlider(this, mMonthYearSetListener, c); case TIMESELECTOR_ID: return new TimeSlider(this, mTimeSetListener, c, 5); case TIMESELECTOR_WITHLIMIT_ID: final Calendar minTime = Calendar.getInstance(); minTime.add(Calendar.HOUR, -2); return new TimeSlider(this, mTimeSetListener, c, 5); case DATETIMESELECTOR_ID: return new DateTimeSlider(this, mDateTimeSetListener, c); } return null; }
public MonthView(@NonNull MaterialCalendarView view, CalendarDay month, int firstDayOfWeek) { super(view.getContext()); this.mcv = view; this.month = month; this.firstDayOfWeek = firstDayOfWeek; setClipChildren(false); setClipToPadding(false); Calendar calendar = resetAndGetWorkingCalendar(); for (int i = 0; i < DEFAULT_DAYS_IN_WEEK; i++) { WeekDayView weekDayView = new WeekDayView(getContext(), CalendarUtils.getDayOfWeek(calendar)); weekDayViews.add(weekDayView); addView(weekDayView); calendar.add(DATE, 1); } calendar = resetAndGetWorkingCalendar(); for (int r = 0; r < DEFAULT_MAX_WEEKS; r++) { for (int i = 0; i < DEFAULT_DAYS_IN_WEEK; i++) { CalendarDay day = CalendarDay.from(calendar); DayView dayView = new DayView(getContext(), day); dayView.setOnClickListener(this); monthDayViews.add(dayView); addView(dayView, new LayoutParams()); calendar.add(DATE, 1); } } }
@Before public void setUp() { dateStart.setTime(DateUtil.parseDateTime("20140101").toDate()); dateStart.set(Calendar.HOUR_OF_DAY, 0); dateStart.set(Calendar.MINUTE, 0); dateStart.set(Calendar.SECOND, 0); dateStart.add(Calendar.HOUR, 12); dateStartLastMinute.setTime(DateUtil.parseDateTime("20140101").toDate()); dateStartLastMinute.set(Calendar.HOUR_OF_DAY, 23); dateStartLastMinute.set(Calendar.MINUTE, 59); dateStartLastMinute.set(Calendar.SECOND, 59); dateStartLastMinute.add(Calendar.HOUR, 12); // creating one list wuth 3 nonMCC accounts Account account1 = new Account(); account1.setId("123"); account1.setTopAccountId(456L); account1.setCanManageClients(false); accountList = ImmutableList.of(account1, account1, account1); storageHelper = new StorageHelper(); mockedRunnableKratu = new RunnableKratu(456L, accountList, storageHelper, dateStart.getTime(), dateEnd); MockitoAnnotations.initMocks(this); when(mockedEntitiesPersister.get(Account.class, "topAccountId", 456L)).thenReturn(accountList); storageHelper.setPersister(mockedEntitiesPersister); }
@SuppressWarnings("unchecked") @Transactional(readOnly = true) public List<RouteEntity> getRoutesByCityIds( String cityFrom, String cityTo, Date date, boolean is3days) { Query q = null; String sql = "SELECT r FROM RouteEntity r WHERE isActive = true AND (" + "(regFrom = :regFrom AND regTo = :regTo ) " + " OR (regFrom = :regFrom AND throughCities LIKE :throughTo) " + " OR (throughCities LIKE :throughFrom AND regTo = :regTo ) " + " OR (throughCities LIKE :throughFrom AND throughCities LIKE :throughTo ) )" + (is3days ? " AND (regDate BETWEEN :lowerDate AND :upperDate) " : " AND regDate = :date ") + " ORDER BY regDate, regTime"; q = em.createQuery(sql); q.setParameter("regFrom", cityFrom); q.setParameter("regTo", cityTo); if (!is3days) { q.setParameter("date", date); } else { Calendar c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.DATE, -3); q.setParameter("lowerDate", c.getTime(), TemporalType.DATE); c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.DATE, 3); q.setParameter("upperDate", c.getTime(), TemporalType.DATE); } q.setParameter("throughTo", "%" + cityTo + "%"); q.setParameter("throughFrom", "%" + cityFrom + "%"); return (List<RouteEntity>) q.getResultList(); }
public DateRange expand(Date d) { Calendar c = new GregorianCalendar(UTC_TZ); c.setTime(d); c.add(this.precision, 1); c.add(Calendar.MILLISECOND, -1); return new DateRange(d, c.getTime()); }
protected static void buildDailyRecurrences( Calendar currentDate, List<Date> dates, Map<String, String> params, Date onOrAfter, Date until, boolean firstOnly, int interval) { // Nice and easy while (currentDate.getTime().before(onOrAfter)) { currentDate.add(Calendar.DATE, 1); } if (firstOnly) { // Save the first date, if valid if (until != null) { if (currentDate.getTime().before(until)) { dates.add(currentDate.getTime()); } } else { dates.add(currentDate.getTime()); } } else { // Run until the end while (currentDate.getTime().before(until)) { dates.add(currentDate.getTime()); currentDate.add(Calendar.DATE, 1); } } }
/** Returns a new Calendar object which is between start and end */ public static Calendar rand(Calendar start, Calendar end) { if (start.after(end)) { Calendar temp = start; start = end; end = temp; } long diff = end.getTime().getTime() - start.getTime().getTime(); long daysDiff = diff / (1000 * 60 * 60 * 24); int delta = rand(0, (int) daysDiff); Calendar newCal = Calendar.getInstance(); newCal.setTime(start.getTime()); newCal.setTimeZone(start.getTimeZone()); newCal.add(Calendar.DAY_OF_MONTH, delta); newCal.add(Calendar.HOUR, rand(0, 23)); newCal.add(Calendar.MINUTE, rand(0, 59)); newCal.add(Calendar.SECOND, rand(0, 59)); // check range cause we might random picked value // greater than the range. if (newCal.after(end)) { newCal.setTime(end.getTime()); newCal.setTimeZone(end.getTimeZone()); } if (newCal.before(start)) { newCal.setTime(start.getTime()); newCal.setTimeZone(start.getTimeZone()); } return newCal; }
public Date getDateFromNow(int days, int hours, int minutes) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, days); cal.add(Calendar.HOUR, hours); cal.add(Calendar.MINUTE, minutes); return cal.getTime(); }
public void testBasicOffsets() { GPCalendarCalc calendar = GPCalendarCalc.PLAIN; Date start = TestSetupHelper.newMonday().getTime(); OffsetBuilder builder = new OffsetBuilderImpl.FactoryImpl() .withStartDate(start) .withViewportStartDate(start) .withCalendar(calendar) .withTopUnit(GPTimeUnitStack.WEEK) .withBottomUnit(GPTimeUnitStack.DAY) .withAtomicUnitWidth(20) .withEndOffset(210) .withWeekendDecreaseFactor(1.0f) .build(); OffsetList bottomUnitOffsets = new OffsetList(); builder.constructOffsets(new ArrayList<Offset>(), bottomUnitOffsets); assertEquals(11, bottomUnitOffsets.size()); assertEquals(20, bottomUnitOffsets.get(0).getOffsetPixels()); assertEquals(220, bottomUnitOffsets.get(10).getOffsetPixels()); Calendar c = (Calendar) Calendar.getInstance().clone(); c.setTime(start); c.add(Calendar.DAY_OF_YEAR, 11); assertEquals(c.getTime(), bottomUnitOffsets.get(10).getOffsetEnd()); c.add(Calendar.DAY_OF_YEAR, -1); assertEquals(c.getTime(), bottomUnitOffsets.get(10).getOffsetStart()); }
private void caricaPubblicazioni() { String testo = "Antichi palazzi costruiti su un'alta collina, un intreccio di viuzze e scalinate, diverse piazzette caratteristiche, un paronama incantevole, unico, l'aria salubre, fresca, questa è Colonnella." + "Le mie \"estati\" sono abruzzesi e quindi conosco bene " + "dell'Abruzzo il colore e il senso dell'estate, quando " + "dai treni che mi riportavano a casa da lontani paesi, " + "passavano per il Tronto e rivedevo le prime case coloniche " + "coi mazzi di granturco sui tetti, le spiagge libere ancora, " + "i paesi affacciati su quei loro balconi naturali di colline, " + "le più belle che io conosca."; Calendar dal = Calendar.getInstance(); dal.setTime(new Date()); dal.add(Calendar.MONTH, -1); Calendar al = Calendar.getInstance(); al.setTime(new Date()); al.add(Calendar.MONTH, 1); TipoPubblicazione tipo = tipoPubblicazioneRepository.find(new Long(4)); for (int i = 0; i < 1000; i++) { Pubblicazione pubblicazione = new Pubblicazione(); pubblicazione.setAl(al.getTime()); pubblicazione.setDal(dal.getTime()); pubblicazione.setAttivo(true); pubblicazione.setAutore("flower"); pubblicazione.setDescrizione(testo); pubblicazione.setNome("pubblicazione" + i); pubblicazione.setTitolo("pubblicazione" + i); pubblicazione.setData(new Date()); pubblicazione.setTipo(tipo); String idTitle = PageUtils.createPageId(pubblicazione.getNome()); String idFinal = testPubbId(idTitle); pubblicazione.setId(idFinal); pubblicazioniRepository.persist(pubblicazione); } }
@Test public void testDoSendFailsWithInvalidTime() throws Exception { IntegrationDefinition integrationDefinition = new IntegrationDefinition("test", providerService, consumerSystem, 5000, true, null, null); EgovWebService service = new EgovWebService("test", 5000, integrationDefinition, echoClient); Calendar from = Calendar.getInstance(); from.add(Calendar.YEAR, 1); Calendar to = Calendar.getInstance(); to.add(Calendar.YEAR, -1); // from integrationDefinition.setValidateFrom(from); integrationDefinition.setValidateTo(null); EgovIntegrationMessage requestMessage = service.createRequestMessage(); EgovIntegrationMessage responseMessage = service.doSend(requestMessage); assertNotNull(responseMessage); assertNotNull(responseMessage.getHeader()); assertEquals(ResultCode.INVALID_TIME, responseMessage.getHeader().getResultCode()); // to integrationDefinition.setValidateFrom(null); integrationDefinition.setValidateTo(to); requestMessage = service.createRequestMessage(); responseMessage = service.doSend(requestMessage); assertNotNull(responseMessage); assertNotNull(responseMessage.getHeader()); assertEquals(ResultCode.INVALID_TIME, responseMessage.getHeader().getResultCode()); }
public static List<Date[]> getDays(Date from, Date to) { List<Date[]> list = new ArrayList<Date[]>(); Date[] fromto; Calendar c = Calendar.getInstance(); c.setTime(from); Calendar cTo = Calendar.getInstance(); cTo.setTime(to); /*fromto = new Date[2]; fromto[0] = c.getTime(); fromto[1] = cTo.getTime(); list.add(fromto); return list;*/ while (c.before(cTo)) { if (c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY || c.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) { Date lFrom = c.getTime(); Calendar lCal = Calendar.getInstance(); lCal.setTime(lFrom); lCal.add(Calendar.DAY_OF_YEAR, 2); Date lTo = lCal.getTime(); fromto = new Date[2]; fromto[0] = lFrom; fromto[1] = lTo; list.add(fromto); } c.add(Calendar.DAY_OF_YEAR, 1); } return list; }
public void testExpireBuffer() throws NoSuchAlgorithmException, NoSuchPaddingException { DefaultTokenCacheStore store = (DefaultTokenCacheStore) setupItems(); ArrayList<TokenCacheItem> tokens = store.getTokensForUser("userid1"); Calendar expireTime = Calendar.getInstance(); Logger.d(TAG, "Time now: " + expireTime.getTime()); expireTime.add(Calendar.SECOND, 240); Logger.d(TAG, "Time modified: " + expireTime.getTime()); // Sets token to expire if less than this buffer AuthenticationSettings.INSTANCE.setExpirationBuffer(300); for (TokenCacheItem item : tokens) { item.setExpiresOn(expireTime.getTime()); assertTrue("Should say expired", TokenCacheItem.isTokenExpired(item.getExpiresOn())); } // Set expire time ahead of buffer 240 +100 secs more than 300secs // buffer expireTime.add(Calendar.SECOND, 100); for (TokenCacheItem item : tokens) { item.setExpiresOn(expireTime.getTime()); assertFalse( "Should not say expired since time is more than buffer", TokenCacheItem.isTokenExpired(item.getExpiresOn())); } }
public static List<Date[]> getDays(int year, int month) { List<Date[]> list = new ArrayList<Date[]>(); Date[] fromto; Calendar c = Calendar.getInstance(); c.clear(); c.set(year, month, 0); int days; if (month >= 0) days = c.getActualMaximum(Calendar.DAY_OF_MONTH); else days = c.getActualMaximum(Calendar.DAY_OF_YEAR); for (int i = 0; i < days; i++) { c.add(Calendar.DAY_OF_YEAR, 1); if (c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY || c.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) { Date from = c.getTime(); c.add(Calendar.DAY_OF_YEAR, 2); Date to = c.getTime(); // Date to = new Date(from.getTime() + (INTERVAL_IN_MS * 2)); fromto = new Date[2]; fromto[0] = from; fromto[1] = to; list.add(fromto); } } return list; }
public int obtenerDiasHabiles(Date fecha, Date fecha2) { Calendar calendario = Calendar.getInstance(); calendario.setTimeZone(TimeZone.getTimeZone("GMT-4:00")); calendario.setTime(fecha2); calendario.add(Calendar.DAY_OF_YEAR, +1); calendario.set(Calendar.HOUR, 0); calendario.set(Calendar.HOUR_OF_DAY, 0); calendario.set(Calendar.SECOND, 0); calendario.set(Calendar.MILLISECOND, 0); calendario.set(Calendar.MINUTE, 0); fecha2 = calendario.getTime(); calendario.setTime(fecha); String fija = formatoFecha.format(fecha2); String hoy = ""; int contador = 0; do { calendario.setTime(fecha); if (calendario.get(Calendar.DAY_OF_WEEK) != 1 && calendario.get(Calendar.DAY_OF_WEEK) != 7) contador++; calendario.add(Calendar.DAY_OF_YEAR, +1); fecha = calendario.getTime(); hoy = formatoFecha.format(fecha); } while (!hoy.equals(fija)); return contador; }
public void setComplaintDate(final String complaintDate) { if (null != complaintDate) { final Date today = new Date(); final Calendar cal = Calendar.getInstance(); if (logger.isDebugEnabled()) logger.debug("String today date... " + ft.format(today)); complaintDateTo = ft.format(today); if (complaintDate.equalsIgnoreCase("today")) { if (logger.isDebugEnabled()) logger.debug("This is today selection"); complaintDateFrom = complaintDateTo; } else if (complaintDate.equalsIgnoreCase("all")) { complaintDateFrom = null; complaintDateTo = null; } else if (complaintDate.equalsIgnoreCase("lastsevendays")) { cal.add(Calendar.DATE, -6); complaintDateFrom = ft.format(cal.getTime()); } else if (complaintDate.equalsIgnoreCase("lastthirtydays")) { cal.add(Calendar.DATE, -29); complaintDateFrom = ft.format(cal.getTime()); } else if (complaintDate.equalsIgnoreCase("lastninetydays")) { cal.add(Calendar.DATE, -89); complaintDateFrom = ft.format(cal.getTime()); } else { if (logger.isDebugEnabled()) logger.debug("Else section in date range"); complaintDateFrom = null; complaintDateTo = null; } } }