Пример #1
0
  public Date calculateGreatestMatchOnOrBefore(Date that) {
    if (equals(UNSPECIFIED)) // Performance improvement
    return null;

    GregorianCalendar gc = that.calculateGC();
    if (year != UNSPECIFIED_YEAR && year < that.year) // Performance improvement
    gc.add(Calendar.YEAR, year - that.year + 1);

    if (!that.sameAs(MAXIMUM_DATE)) {
      // Start a day ahead
      gc.add(Calendar.DATE, 1);
    }
    Date date = new Date(gc);

    boolean matched = matches(date);
    while (true) {
      gc.add(Calendar.DATE, -1);
      date.resetTo(gc);
      boolean b = matches(date);
      if (!b && matched) matched = false;
      else if (!matched && b) break;
      if (date.sameAs(MINIMUM_DATE)) return null;
      if (year != UNSPECIFIED_YEAR && year > date.year) // Performance improvement
      return null;
    }

    return date;
  }
  /* (non-Javadoc)
   * @see net.finmath.time.daycount.DayCountConventionInterface#getDaycountFraction(java.util.GregorianCalendar, java.util.GregorianCalendar)
   */
  @Override
  public double getDaycountFraction(Calendar startDate, Calendar endDate) {
    if (startDate.after(endDate)) return -getDaycountFraction(endDate, startDate);

    /*
     * Number of whole years between start and end. If start and end fall in the same year, this is -1 (there will be a double counting of 1 year below if start < end).
     */
    double daycountFraction = endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR) - 1.0;

    /*
     * Fraction from start to the end of start's year
     */
    GregorianCalendar startDateNextYear = (GregorianCalendar) startDate.clone();
    startDateNextYear.set(Calendar.DAY_OF_YEAR, 1);
    startDateNextYear.add(Calendar.YEAR, 1);
    if (isCountLastDayNotFirst) startDateNextYear.add(Calendar.DAY_OF_YEAR, -1);

    daycountFraction +=
        getDaycount(startDate, startDateNextYear)
            / startDate.getActualMaximum(Calendar.DAY_OF_YEAR);

    /*
     * Fraction from beginning of end's year to end
     */
    GregorianCalendar endDateStartYear = (GregorianCalendar) endDate.clone();
    endDateStartYear.set(Calendar.DAY_OF_YEAR, 1);
    if (isCountLastDayNotFirst) endDateStartYear.add(Calendar.DAY_OF_YEAR, -1);

    daycountFraction +=
        getDaycount(endDateStartYear, endDate) / endDate.getActualMaximum(Calendar.DAY_OF_YEAR);

    return Math.max(daycountFraction, 0.0);
  }
Пример #3
0
  private void updateCalendarLocale(Locale l) {
    int oldFirstDayOfWeek = calendar.getFirstDayOfWeek();
    setLocale(l);
    calendarComponent.setLocale(l);
    calendar = new GregorianCalendar(l);
    int newFirstDayOfWeek = calendar.getFirstDayOfWeek();

    // we are showing 1 week, and the first day of the week has changed
    // update start and end dates so that the same week is showing
    if (viewMode == Mode.WEEK && oldFirstDayOfWeek != newFirstDayOfWeek) {
      calendar.setTime(calendarComponent.getStartDate());
      calendar.add(java.util.Calendar.DAY_OF_WEEK, 2);
      // starting at the beginning of the week
      calendar.set(GregorianCalendar.DAY_OF_WEEK, newFirstDayOfWeek);
      Date start = calendar.getTime();

      // ending at the end of the week
      calendar.add(GregorianCalendar.DATE, 6);
      Date end = calendar.getTime();

      calendarComponent.setStartDate(start);
      calendarComponent.setEndDate(end);

      // Week days depend on locale so this must be refreshed
      setWeekendsHidden(hideWeekendsButton.getValue());
    }
  }
Пример #4
0
  public Date calculateLeastMatchOnOrBefore(Date that) {
    if (equals(UNSPECIFIED)) // Performance improvement
    return MINIMUM_DATE;

    boolean matched = matches(that);
    GregorianCalendar gc = that.calculateGC();

    if (year != UNSPECIFIED_YEAR && year < that.year) // Performance improvement
    gc.add(Calendar.YEAR, year - that.year + 1);

    Date date = new Date(gc);
    while (true) {
      if (date.sameAs(MINIMUM_DATE)) return matched ? date : null;
      gc.add(Calendar.DATE, -1);
      date.resetTo(gc);
      boolean b = matches(date);
      if (b && !matched) matched = true;
      else if (matched && !b) break;
      if (year != UNSPECIFIED_YEAR && year > date.year) // Performance improvement
      return null;
    }

    gc.add(Calendar.DATE, 1);
    date.resetTo(gc);
    return date;
  }
Пример #5
0
  /**
   * Create 12 Standard Periods from the specified start date. Creates also Period Control from
   * DocType.
   *
   * @see DocumentTypeVerify#createPeriodControls(Properties, int, SvrProcess, String)
   * @param locale locale
   * @param startDate first day of the calendar year
   * @param dateFormat SimpleDateFormat pattern for generating the period names.
   * @return true if created
   */
  public boolean createStdPeriods(Locale locale, Timestamp startDate, String dateFormat) {
    if (locale == null) {
      MClient client = MClient.get(getCtx());
      locale = client.getLocale();
    }

    if (locale == null && Language.getLoginLanguage() != null)
      locale = Language.getLoginLanguage().getLocale();
    if (locale == null) locale = Env.getLanguage(getCtx()).getLocale();
    //
    SimpleDateFormat formatter;
    if (dateFormat == null || dateFormat.equals("")) dateFormat = "MMM-yy";
    formatter = new SimpleDateFormat(dateFormat, locale);

    //
    int year = getYearAsInt();
    GregorianCalendar cal = new GregorianCalendar(locale);
    if (startDate != null) {
      cal.setTime(startDate);
      if (cal.get(Calendar.YEAR) != year) // specified start date takes precedence in setting year
      year = cal.get(Calendar.YEAR);

    } else {
      cal.set(Calendar.YEAR, year);
      cal.set(Calendar.MONTH, 0);
      cal.set(Calendar.DAY_OF_MONTH, 1);
    }
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    //
    for (int month = 0; month < 12; month++) {

      Timestamp start = new Timestamp(cal.getTimeInMillis());
      String name = formatter.format(start);
      // get last day of same month
      cal.add(Calendar.MONTH, 1);
      cal.add(Calendar.DAY_OF_YEAR, -1);
      Timestamp end = new Timestamp(cal.getTimeInMillis());
      //
      MPeriod period = MPeriod.findByCalendar(getCtx(), start, getC_Calendar_ID(), get_TrxName());
      if (period == null) {
        period = new MPeriod(this, month + 1, name, start, end);
      } else {
        period.setC_Year_ID(this.getC_Year_ID());
        period.setPeriodNo(month + 1);
        period.setName(name);
        period.setStartDate(start);
        period.setEndDate(end);
      }
      period.saveEx(get_TrxName()); // 	Creates Period Control
      // get first day of next month
      cal.add(Calendar.DAY_OF_YEAR, 1);
    }

    return true;
  } //	createStdPeriods
 private static void createOverdueLoanForCopy(Library library, Copy copy, int position)
     throws IllegalLoanOperationException {
   Loan l = library.createAndAddLoan(getCustomer(library, position), copy);
   GregorianCalendar pickup = l.getPickupDate();
   pickup.add(GregorianCalendar.MONTH, -1);
   pickup.add(GregorianCalendar.DAY_OF_MONTH, -position % 15);
   l.setPickupDate(pickup);
 }
Пример #7
0
 private void rollWeek(int direction) {
   calendar.add(GregorianCalendar.WEEK_OF_YEAR, direction);
   calendar.set(GregorianCalendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
   resetCalendarTime(false);
   resetTime(true);
   calendar.add(GregorianCalendar.DATE, 6);
   calendarComponent.setEndDate(calendar.getTime());
 }
  public void testWheelchairAccessible() throws Exception {
    Vertex near_a = graph.getVertex("near_1_agency_entrance_a");
    Vertex near_b = graph.getVertex("near_1_agency_entrance_b");
    Vertex near_c = graph.getVertex("near_1_agency_C");
    Vertex near_e = graph.getVertex("near_1_agency_E");

    Vertex stop_d = graph.getVertex("agency:D");
    Vertex split_d = null;
    for (StreetTransitLink e : Iterables.filter(stop_d.getOutgoing(), StreetTransitLink.class)) {
      split_d = e.getToVertex();
    }

    RoutingRequest options = new RoutingRequest();
    options.wheelchairAccessible = true;
    options.dateTime = TestUtils.dateInSeconds("America/New_York", 2009, 8, 18, 0, 0, 0);

    ShortestPathTree spt;
    GraphPath path;

    // stop B is accessible, so there should be a path.
    options.setRoutingContext(graph, near_a, near_b);
    spt = aStar.getShortestPathTree(options);

    path = spt.getPath(near_b, false);
    assertNotNull(path);

    // stop C is not accessible, so there should be no path.
    options.setRoutingContext(graph, near_a, near_c);
    spt = aStar.getShortestPathTree(options);

    path = spt.getPath(near_c, false);
    assertNull(path);

    // stop E has no accessibility information, but we should still be able to route to it.
    options.setRoutingContext(graph, near_a, near_e);
    spt = aStar.getShortestPathTree(options);

    path = spt.getPath(near_e, false);
    assertNotNull(path);

    // from stop A to stop D would normally be trip 1.1 to trip 2.1, arriving at 00:30. But trip
    // 2 is not accessible, so we'll do 1.1 to 3.1, arriving at 01:00
    GregorianCalendar time = new GregorianCalendar(2009, 8, 18, 0, 0, 0);
    time.setTimeZone(TimeZone.getTimeZone("America/New_York"));
    options.dateTime = TestUtils.toSeconds(time);
    options.setRoutingContext(graph, near_a, split_d);
    spt = aStar.getShortestPathTree(options);

    time.add(Calendar.HOUR, 1);
    time.add(Calendar.SECOND, 1); // for the StreetTransitLink
    path = spt.getPath(split_d, false);
    assertNotNull(path);
    assertEquals(TestUtils.toSeconds(time), path.getEndTime());
  }
Пример #9
0
 private String[] getTimeSpan(GregorianCalendar dateTime, int increment) {
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
   sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
   String sTime = sdf.format(dateTime.getTime());
   String eTime = null;
   if (increment != -1) {
     /** Add the increment and then subtract 1 second so that the timespans do not overlap. */
     dateTime.add(GregorianCalendar.MILLISECOND, increment);
     dateTime.add(GregorianCalendar.SECOND, -1);
     eTime = sdf.format(dateTime.getTime());
   }
   return new String[] {sTime, eTime};
 }
Пример #10
0
  private void rollMonth(int direction) {
    calendar.setTime(currentMonthsFirstDate);
    calendar.add(GregorianCalendar.MONTH, direction);
    resetTime(false);
    currentMonthsFirstDate = calendar.getTime();
    calendarComponent.setStartDate(currentMonthsFirstDate);

    updateCaptionLabel();

    calendar.add(GregorianCalendar.MONTH, 1);
    calendar.add(GregorianCalendar.DATE, -1);
    resetCalendarTime(true);
  }
Пример #11
0
 /**
  * Set calendar to this week's Monday; set year and week combo boxes to the currently set date;
  * set the date labels appropriately; and, refresh the review table.
  */
 private void updateYearWeekDates() {
   yearWeekCalendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
   yearWeekCalendar.set(Calendar.HOUR_OF_DAY, 0);
   yearWeekCalendar.set(Calendar.MINUTE, 0);
   yearWeekCalendar.set(Calendar.SECOND, 0);
   yearWeekCalendar.set(Calendar.MILLISECOND, 0);
   yearCB.setSelectedItem(yearWeekCalendar.get(Calendar.YEAR));
   weekCB.setSelectedItem(yearWeekCalendar.get(Calendar.WEEK_OF_YEAR));
   fromDate.setDate(yearWeekCalendar);
   yearWeekCalendar.add(Calendar.DAY_OF_MONTH, 7);
   toDate.setDate(yearWeekCalendar);
   yearWeekCalendar.add(Calendar.DAY_OF_MONTH, -7);
   refreshReviewTable();
 }
Пример #12
0
  public static void main(String[] args) {
    Logger logger = Logger.getLogger(Main.class);
    Date fTime = new Date();
    Date tTime = new Date();
    if (args.length == 2) {
      fTime = MyUtil.StringToDate(args[0]);
      tTime = MyUtil.StringToDate(args[1]);
    }
    if (args.length == 0) {
      Calendar fromWhen = Calendar.getInstance();
      fromWhen.setTime(fTime);
      GregorianCalendar gc =
          new GregorianCalendar(
              fromWhen.get(Calendar.YEAR),
              fromWhen.get(Calendar.MONTH),
              fromWhen.get(Calendar.DAY_OF_MONTH));
      tTime = (Date) gc.getTime();
      gc.add(Calendar.DATE, -1);
      fTime = (Date) gc.getTime();
    }
    logger.info("Stats process start " + new Date());

    long flag = (tTime.getTime() - fTime.getTime()) / 1000 / 3600 / 24;
    for (long temp = 0; temp < flag; temp++) {
      Calendar fromWhen = Calendar.getInstance();
      fromWhen.setTime(fTime);
      GregorianCalendar gc =
          new GregorianCalendar(
              fromWhen.get(Calendar.YEAR),
              fromWhen.get(Calendar.MONTH),
              fromWhen.get(Calendar.DAY_OF_MONTH));
      gc.add(Calendar.DATE, 1);
      tTime = (Date) gc.getTime();

      System.out.print(fTime);
      System.out.print("----");
      System.out.println(tTime);

      GoldStats.setAllGold(fTime);
      GoldStats.setAllPearl(fTime);
      GoldStats.setAllCredit(fTime);
      StockStats.StartStats(fTime);
      // 家族等级分布
      TribeStats.setAllTribeLevel(fTime);

      fTime = tTime;
    }
    logger.info("Stats process end " + new Date());
  }
Пример #13
0
  @Test
  public void testFindByDate() {

    Company company = new CompanyBuilder().build();

    Candidate candidate1 =
        new CandidateBuilder()
            .withName(new Name("Candidate1"))
            .withEmail("*****@*****.**")
            .withCompany(company)
            .build();
    Candidate candidate2 =
        new CandidateBuilder().withName(new Name("Candidate2")).withCompany(company).build();
    Candidate candidate3 =
        new CandidateBuilder().withName(new Name("Candidate3")).withCompany(company).build();

    companyDao.save(company);
    candidateDao.save(candidate1);
    candidateDao.save(candidate2);
    candidateDao.save(candidate3);

    GregorianCalendar start = new GregorianCalendar();
    start.add(Calendar.HOUR_OF_DAY, -24);
    GregorianCalendar end = new GregorianCalendar();

    List<Candidate> results = candidateDao.findByCompanyIDandDateRange(company.getId(), start, end);
    assertEquals(3, results.size());
  }
Пример #14
0
  public static java.util.Date proximoDiaMesAtual(java.util.Date data) {
    GregorianCalendar gcTmp = new GregorianCalendar();
    gcTmp.setTime(data);
    gcTmp.add(5, 1);

    return gcTmp.getTime();
  }
Пример #15
0
  public static void save(MJEvaluation evaluation, Long appraisers[]) throws Exception {
    Policy policy =
        Policy.getInstance(
            Play.applicationPath.getAbsolutePath() + "/conf/antisamy-myspace-1.3.xml");
    AntiSamy as = new AntiSamy();
    CleanResults cr = as.scan(evaluation.content, policy);
    User editor = User.loadFromSession();

    evaluation.actif = false;
    evaluation.editor = editor.person;
    evaluation.evaluationDate = new GregorianCalendar();

    List<Person> employes = new ArrayList<Person>();
    for (Long id : appraisers) {
      employes.add((Person) Person.findById(id));
    }

    evaluation.appraisers = employes;
    evaluation.save();

    MJEvaluation newEvaluation = new MJEvaluation();
    GregorianCalendar date = new GregorianCalendar();
    date.setTimeInMillis(evaluation.evaluationDate.getTimeInMillis());
    date.add(Calendar.MONTH, 6);

    evaluation.actif = true;
    newEvaluation.evaluationDate = date;
    newEvaluation.resident = evaluation.resident;
    newEvaluation.save();

    flash.success("saved");

    MJEvaluations.show(evaluation.resident.id);
  }
Пример #16
0
  @Test
  public void testTick() {
    IMocksControl control = createControl();

    GregorianCalendar startDateMock = control.createMock(GregorianCalendar.class);
    GregorianCalendar startDateCloneMock = control.createMock(GregorianCalendar.class);
    expect(startDateMock.clone()).andReturn(startDateCloneMock).once();
    GregorianCalendar currentDateCloneMock = control.createMock(GregorianCalendar.class);
    expect(startDateCloneMock.clone()).andReturn(currentDateCloneMock).once();

    startDateCloneMock.add(Calendar.DAY_OF_MONTH, 1);

    EventBus eventBusMock = control.createMock(EventBus.class);
    eventBusMock.post(anyObject(TimeTickEvent.class));
    expectLastCall().once();

    control.replay();

    TimeManagerImpl manager =
        new TimeManagerImpl(startDateMock, Calendar.DAY_OF_MONTH, 1, eventBusMock);
    Calendar newDate = manager.tick();

    assertEquals(startDateCloneMock, newDate);

    control.verify();
  }
Пример #17
0
 /**
  * Calcula si un alumno esta expulsado. Se sabe si un alumno está expulsado por el número de dias
  * escolares entre la fecha de expulsión y la de parte. Un día escolar es el numero de partes con
  * fecha distinta entre dos fechas.
  *
  * @param anoEscolar Año escola
  * @param alumno Alumno
  * @param fecha Fecha en la que se quiere saber si el alumno estça expulsado
  * @return true si está expulsado en la fecha del parte, false si no lo está
  */
 public static Boolean isAlumnoExpulsado(Alumno alumno, GregorianCalendar fecha) {
   boolean ret = false;
   try {
     // Tenemos que ver si hay expulsiones para ese alumno
     PreparedStatement st =
         (PreparedStatement)
             MaimonidesApp.getApplication()
                 .getConector()
                 .getConexion()
                 .prepareStatement("SELECT * FROM expulsiones WHERE alumno_id=? AND fecha<=?");
     st.setInt(1, alumno.getId());
     st.setDate(2, new java.sql.Date(fecha.getTimeInMillis()));
     ResultSet res = st.executeQuery();
     while (res.next() && !ret) {
       // Si hay expulsiones tenemos que ver si son válidas
       // Para eso tenemos que contar los partes desde la fecha de expulsión hasta ahora
       GregorianCalendar fechaExpulsion = Fechas.toGregorianCalendar(res.getDate("fecha"));
       if (fechaExpulsion != null) {
         // Como la fecha de expulsión esta incluida tenemos que quitarle un día
         fechaExpulsion.add(GregorianCalendar.DATE, -1);
         // Y vemos la diferencia en días
         int dias = res.getInt("dias");
         long diasTranscurridos =
             Fechas.getDiferenciaTiempoEn(fecha, fechaExpulsion, GregorianCalendar.DATE);
         ret = diasTranscurridos <= dias;
       }
     }
     Obj.cerrar(st, res);
   } catch (SQLException ex) {
     Logger.getLogger(Expulsion.class.getName()).log(Level.SEVERE, null, ex);
   }
   return ret;
 }
Пример #18
0
  /**
   * Contract: get SheduleItems that ID equals to inSheduleItem.getId(); compare if the train
   * capacity more then current tickets count on this SheduleItem; compare if the date of departure
   * more then current date for 10 minutes
   *
   * @param inSheduleItem SheduleItem for which need checks
   * @return SheduleItem selected from database or throws exceptions
   * @throws NoAvailableSeatsException
   * @throws ExpiredTimeToBuyException
   */
  @Transactional(readOnly = false, rollbackFor = Exception.class)
  public SheduleItemEntity checkTrainSeatsAndDate(SheduleItemEntity inSheduleItem)
      throws NoAvailableSeatsException, ExpiredTimeToBuyException {

    SheduleItemEntity sheduleItem =
        (SheduleItemEntity) this.sheduleDAO.getById(SheduleItemEntity.class, inSheduleItem.getId());
    /*check available seats*/
    List<SheduleItemEntity> sheduleItemsList = new ArrayList<SheduleItemEntity>();
    sheduleItemsList.add(sheduleItem);
    sheduleItemsList = this.sheduleDAO.getBySheduleItems(sheduleItemsList);
    if (sheduleItem.getTrain().getCapacity() == sheduleItemsList.get(0).getTicketsList().size()) {
      throw new NoAvailableSeatsException();
    }

    /*check that before departure left 10 minutes*/
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.setTime(new Date());

    GregorianCalendar departureDateMinus10 = new GregorianCalendar();
    departureDateMinus10.setTime(sheduleItem.getDepartureDate());
    departureDateMinus10.add(GregorianCalendar.MINUTE, -10);

    if (currentDate.after(departureDateMinus10)) {
      throw new ExpiredTimeToBuyException();
    }

    return sheduleItem;
  }
Пример #19
0
  public static Date getDatePlusMinutes(final Date date, final int minutes) {
    final GregorianCalendar dateCalendar = new GregorianCalendar();
    dateCalendar.setTime(date);
    dateCalendar.add(Calendar.MINUTE, minutes);

    return dateCalendar.getTime();
  }
 private Date newestDateToDelete() {
   GregorianCalendar calendar = new GregorianCalendar();
   calendar.setTime(clock.now());
   calendar.add(Calendar.DAY_OF_YEAR, -settings.getRequestLogCleanupMaxAgeDays());
   Date newestDateToDelete = calendar.getTime();
   return newestDateToDelete;
 }
 public String obtenerFecha(String formato, int diferencia) {
   GregorianCalendar gcalendar = new GregorianCalendar();
   gcalendar.add(5, diferencia);
   java.util.Date d = gcalendar.getTime();
   SimpleDateFormat sdf = new SimpleDateFormat(formato);
   return sdf.format(d);
 }
  private void showNotAccessedInNDays(Vector vector, Document document) {
    int i = getPropertyAsInteger(pNotAccessedN);
    if (i > 0) {
      Vector vector1 = new Vector();
      GregorianCalendar gregoriancalendar = new GregorianCalendar();
      gregoriancalendar.setTime(new Date());
      gregoriancalendar.add(6, -i);
      Date date = gregoriancalendar.getTime();
      for (int j = 0; j < vector.size(); j++) {
        Map map = (Map) vector.elementAt(j);
        Date date1 = (Date) map.get("JavaLastLogoffTime");
        if (date1 == null || date1.getTime() >= date.getTime()) {
          continue;
        }
        Vector vector2 = new Vector();
        vector1.addElement(vector2);
        vector2.addElement(new Pair("Mailbox", map.get("MailboxDisplayName")));
        synchronized (mDisplayDateFormat) {
          vector2.addElement(new Pair("Last Logoff Time", mDisplayDateFormat.format(date1)));
        }
      }

      addListContent(vector1, "Mailboxes Not Accessed in " + i + " Days", document);
    }
  }
Пример #23
0
  public static void main(String[] args) {
    // Creates a GregorianCalendar object for the quizDay, outputs
    // information about the day, and modifies the day using class
    // methods
    // Creates the quizday object to store the day of the quiz

    GregorianCalendar quizDay = new GregorianCalendar(2014, Calendar.OCTOBER, 10);

    int month, day; // store date attributes
    // Get integer value for the characteristics
    day = quizDay.get(Calendar.DAY_OF_MONTH);
    System.out.println("Day: " + day);
    month = quizDay.get(Calendar.MONTH);
    System.out.println("Month: " + month);

    // Make the quiz 4 days earlier
    // Get the new date
    quizDay.add(Calendar.DAY_OF_MONTH, -4);
    day = quizDay.get(Calendar.DAY_OF_MONTH);
    System.out.println("Day of the quiz: " + day);
    month = quizDay.get(Calendar.MONTH);
    System.out.println("Month of the quiz: " + month);

    // Format the output of the date using DateFormat
    DateFormat fmt = DateFormat.getInstance();
    System.out.println("Formatted Date: " + fmt.format(quizDay.getTime()));
  }
Пример #24
0
 /**
  * 自定义时间timer 增减 月
  *
  * @param fmtTimer
  * @param amount
  * @return
  */
 public static Long addMonthFmtTimer(Long fmtTimer, int amount) {
   Date cDate = myTimerToDate(fmtTimer);
   GregorianCalendar cal = new GregorianCalendar();
   cal.setTime(cDate);
   cal.add(GregorianCalendar.MONTH, amount);
   return dateFmtTimer(cal.getTime());
 }
Пример #25
0
 private void handleCommand(Intent intent) {
   Task task = TaskHelper.getTaskFromIntent(intent);
   if (task == null) return;
   if (intent.getAction() == TASK_DONE) {
     task.setDone(true);
     task.safeSave();
     Toast.makeText(
             this, getString(R.string.reminder_notification_done_confirm), Toast.LENGTH_LONG)
         .show();
   } else if (intent.getAction() == TASK_LATER && !task.hasRecurringReminder()) {
     GregorianCalendar reminder = new GregorianCalendar();
     int addMinutes = MirakelCommonPreferences.getAlarmLater();
     reminder.add(Calendar.MINUTE, addMinutes);
     task.setReminder(reminder);
     task.safeSave();
     Toast.makeText(
             this,
             getString(R.string.reminder_notification_later_confirm, addMinutes),
             Toast.LENGTH_LONG)
         .show();
   }
   ReminderAlarm.closeNotificationFor(this, task.getId());
   ReminderAlarm.updateAlarms(this);
   stopSelf();
 }
Пример #26
0
 /**
  * 当前时间+指定时间间隔(秒为单位)
  *
  * <p>by baijm 2010-11-09
  *
  * @param date
  * @param num
  * @return java.util.Date
  * @throws AppException
  */
 public static Date addSeconds(Date date, int num) throws AppException {
   if (null == date) throw new AppException("", "缺少参数!");
   GregorianCalendar cal = new GregorianCalendar();
   cal.setTime(date);
   cal.add(GregorianCalendar.SECOND, num);
   return cal.getTime();
 }
Пример #27
0
 /**
  * @param days=n n为-,则取n天前,n为+,则取n天后的日期
  * @param date
  * @param days
  * @return
  */
 public Date getSomeDaysBeforeAfter(Date date, int days) {
   GregorianCalendar gc = new GregorianCalendar();
   gc.setTime(date);
   gc.add(5, days);
   gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DATE));
   return gc.getTime();
 }
Пример #28
0
 public int getMonths(GregorianCalendar g1, GregorianCalendar g2) {
   int elapsed = 0;
   GregorianCalendar gc1, gc2;
   if (g2.after(g1)) {
     gc2 = (GregorianCalendar) g2.clone();
     gc1 = (GregorianCalendar) g1.clone();
   } else {
     gc2 = (GregorianCalendar) g1.clone();
     gc1 = (GregorianCalendar) g2.clone();
   }
   gc1.clear(Calendar.MILLISECOND);
   gc1.clear(Calendar.SECOND);
   gc1.clear(Calendar.MINUTE);
   gc1.clear(Calendar.HOUR_OF_DAY);
   gc1.clear(Calendar.DATE);
   gc2.clear(Calendar.MILLISECOND);
   gc2.clear(Calendar.SECOND);
   gc2.clear(Calendar.MINUTE);
   gc2.clear(Calendar.HOUR_OF_DAY);
   gc2.clear(Calendar.DATE);
   while (gc1.before(gc2)) {
     gc1.add(Calendar.MONTH, 1);
     elapsed++;
   }
   return elapsed;
 }
Пример #29
0
  private void initCalendar() {
    dataSource = new BasicEventProvider();

    calendarComponent = new Calendar(dataSource);
    calendarComponent.setLocale(getLocale());
    calendarComponent.setImmediate(true);

    if (calendarWidth != null || calendarHeight != null) {
      if (calendarHeight != null) {
        calendarComponent.setHeight(calendarHeight);
      }
      if (calendarWidth != null) {
        calendarComponent.setWidth(calendarWidth);
      }
    } else {
      calendarComponent.setSizeFull();
    }

    if (firstHour != null && lastHour != null) {
      calendarComponent.setFirstVisibleHourOfDay(firstHour);
      calendarComponent.setLastVisibleHourOfDay(lastHour);
    }

    if (firstDay != null && lastDay != null) {
      calendarComponent.setFirstVisibleDayOfWeek(firstDay);
      calendarComponent.setLastVisibleDayOfWeek(lastDay);
    }

    Date today = getToday();
    calendar = new GregorianCalendar(getLocale());
    calendar.setTime(today);

    updateCaptionLabel();

    if (!showWeeklyView) {
      int rollAmount = calendar.get(GregorianCalendar.DAY_OF_MONTH) - 1;
      calendar.add(GregorianCalendar.DAY_OF_MONTH, -rollAmount);
      resetTime(false);
      currentMonthsFirstDate = calendar.getTime();
      calendarComponent.setStartDate(currentMonthsFirstDate);
      calendar.add(GregorianCalendar.MONTH, 1);
      calendar.add(GregorianCalendar.DATE, -1);
      calendarComponent.setEndDate(calendar.getTime());
    }

    addCalendarEventListeners();
  }
Пример #30
0
  /**
   * This method should be implemented in any subclasses of this component interested in processing
   * parameters from an html post operation. The component should interogate the HttpServletRequest
   * for any parameters it is interested in and change its internal state to reflect the parms.
   *
   * @return true if this component is the one that submitted the page and false if not.
   * @param parms a HashTable containing all the parameters for the servlet.
   */
  public boolean processParms(Hashtable parms, int rowNo) throws Exception {

    Object parm = parms.get(getFullName());
    if (parm == null) return false;

    String[] command = (String[]) parm;

    if (command[0] == null || command[0].trim().equals("")) return false;

    String st[] = getLookupComponent();
    if (command[0].startsWith("changeMonth:")) {
      int monthInc = Integer.parseInt(command[0].substring(12));
      GregorianCalendar g = new GregorianCalendar(_currentYear, _currentMonth, 1);
      g.add(Calendar.MONTH, monthInc);
      CalendarMonthChangeEvent e =
          new CalendarMonthChangeEvent(
              this, _currentMonth, _currentYear, g.get(Calendar.MONTH), g.get(Calendar.YEAR));
      _calEvent = e;
      if (st != null) {
        _scrollTo = true;
        getPage().scrollToItem(getFullName() + "CalStart");
      }
    } else if (command[0].startsWith("selectDate:")) {
      String newDate = command[0].substring(11);
      int pos = newDate.indexOf("-");
      String day = newDate.substring(0, pos);
      String year = newDate.substring(pos + 1);

      int dayInt = Integer.parseInt(day);
      int yearInt = Integer.parseInt(year);

      GregorianCalendar g = new GregorianCalendar();
      g.set(Calendar.YEAR, yearInt);
      g.set(Calendar.DAY_OF_YEAR, dayInt);

      java.sql.Date d = new java.sql.Date(g.getTime().getTime());
      CalendarDateSelectedEvent e = new CalendarDateSelectedEvent(this, g, d);

      _calEvent = e;

      if (st == null) {
        _scrollTo = true;
        getPage().scrollToItem(getFullName() + "CalStart");
      } else {
        HtmlScriptGenerator gen = new HtmlScriptGenerator(getPage());
        String format = st[1];
        String dtString = null;
        if (format != null) {
          SimpleDateFormat df = new SimpleDateFormat(format);
          dtString = df.format(d);
        } else {
          dtString = d.toString();
        }
        getPage().writeScript(gen.generateReturnValueToLookupScript(dtString, ""));
      }
    }

    return true;
  }