@Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
          chosenDateTime.set(Calendar.YEAR, year);
          chosenDateTime.set(Calendar.MONTH, monthOfYear);
          chosenDateTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
          calFuture = Calendar.getInstance();
          calFuture.add(Calendar.DAY_OF_MONTH, 30);
          dateBool = false;
          if (calToday.after(chosenDateTime))
            Toast.makeText(
                    MainActivity2.this, "Please pick a date in the future!", Toast.LENGTH_SHORT)
                .show();
          else if (chosenDateTime.after(calFuture))
            Toast.makeText(
                    MainActivity2.this,
                    "Appointments cannot be set for more than 30 days in the future!",
                    Toast.LENGTH_SHORT)
                .show();
          else if (chosenDateTime.get(Calendar.DAY_OF_WEEK) == 1
              || chosenDateTime.get(Calendar.DAY_OF_WEEK) == 7)
            Toast.makeText(MainActivity2.this, "We are closed on weekends!", Toast.LENGTH_SHORT)
                .show();
          else dateBool = true;

          setCurrentDateOnView();
        }
示例#2
0
  public void updateGameList() throws RemoteException, InvalidSessionException {
    final String user = usrMgr.getSession().getUser();
    final ArrayList<GameInfo> fullList = srvAdapter.fetchGameList(usrMgr.getSession());
    final ArrayList<GameInfo> currentList = new ArrayList<GameInfo>();
    final ArrayList<GameInfo> openList = new ArrayList<GameInfo>();
    final Calendar now = Calendar.getInstance();
    final Calendar now2h = Calendar.getInstance();
    now2h.add(Calendar.HOUR, -2);

    for (final GameInfo info : fullList) {
      if (info.getPlayers().contains(user)) {
        for (final Calendar c : info.getGameSessions()) {
          if (c.before(now) && c.after(now2h)) {
            currentList.add(info);
            break;
          }
        }
      } else if (info.getnFreeTerritories() > 0) {
        for (final Calendar c : info.getGameSessions()) {
          if (c.after(now2h)) {
            openList.add(info);
            break;
          }
        }
      }
    }

    mCurrentGameListModel.setData(currentList);
    mOpenGameListModel.setData(openList);
  }
示例#3
0
  /** 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;
  }
  /**
   * Updates the view list of available rooms
   *
   * @param checkIn check-in date
   * @param checkOut check-out date
   * @param type room type
   */
  public void updateViewData(Calendar checkIn, Calendar checkOut, double type) {
    viewData.clear();

    for (int i = 0; i < roomList.size(); i++) { // traverses roomList
      Room room = roomList.get(i); // <---room to be added to the available rooms list
      if (room.noReservations()) {
        viewData.add(roomList.get(i));
        for (ChangeListener l : listeners) {
          l.stateChanged(new ChangeEvent(this));
        }
      } else { // if a room has reservations, check each reservation for conflicting dates
        // SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/YYYY");

        boolean flag = false;

        for (int j = 0;
            j < room.reservations.size();
            j++) { // traverses room's list of reservations
          Reservation r = room.reservations.get(j);

          if ((checkIn.before(r.checkInDate) || checkIn.after(r.checkOutDate))
              && (checkOut.before(r.checkInDate) || checkOut.after(r.checkOutDate))
              && (checkIn.compareTo(r.checkInDate) != 0
                  && checkOut.compareTo(r.checkOutDate) != 0)) {
            flag = true; // okay to add
          } else {
            flag = false;
          }
        }
        if (flag) {
          viewData.add(room);
          for (ChangeListener l : listeners) {
            l.stateChanged(new ChangeEvent(this));
          }
        }
      }
    }
    if (type == 0) {
      viewData.clear();
    } else {
      for (int k = 0; k < viewData.size(); k++) {
        double temp = viewData.get(k).getRate();
        if (temp != type) {
          System.out.println("viewData rate: " + viewData.get(k).getRate());
          System.out.println("Type: " + type);
          viewData.remove(k);
        }
      }
      for (ChangeListener l : listeners) {
        l.stateChanged(new ChangeEvent(this));
      }
    }
  }
  @Override
  public VulnerabilityDefectConsistencyState determineVulnerabilityDefectConsistencyState(
      Vulnerability vulnerability) {
    VulnerabilityDefectConsistencyState vulnerabilityDefectConsistencyState = null;

    Defect defect = vulnerability.getDefect();
    if (defect != null) {
      if (vulnerability.isActive() == defect.isOpen()) {
        vulnerabilityDefectConsistencyState = VulnerabilityDefectConsistencyState.CONSISTENT;
      } else if (defect.isOpen()) {
        vulnerabilityDefectConsistencyState =
            VulnerabilityDefectConsistencyState.VULN_CLOSED_DEFECT_OPEN_NEEDS_SCAN;
      } else {
        Calendar latestScanDate = null;
        for (Finding finding : vulnerability.getFindings()) {
          Calendar scanDate = finding.getScan().getImportTime();
          if ((latestScanDate == null) || scanDate.after(latestScanDate)) {
            latestScanDate = scanDate;
          }
          if (finding.getScanRepeatFindingMaps() != null) {
            for (ScanRepeatFindingMap scanRepeatFindingMap : finding.getScanRepeatFindingMaps()) {
              Scan scan = scanRepeatFindingMap.getScan();
              if (scan != null) {
                scanDate = scan.getImportTime();
                if ((latestScanDate == null) || scanDate.after(latestScanDate)) {
                  latestScanDate = scanDate;
                }
              }
            }
          }
        }
        Calendar defectStatusUpdatedDate = defect.getStatusUpdatedDate();
        if (defectStatusUpdatedDate == null) {
          defectStatusUpdatedDate = Calendar.getInstance();
          defectStatusUpdatedDate.setTime(defect.getModifiedDate());
        }
        if ((latestScanDate != null) && latestScanDate.after(defectStatusUpdatedDate)) {
          vulnerabilityDefectConsistencyState =
              VulnerabilityDefectConsistencyState.VULN_OPEN_DEFECT_CLOSED_STILL_IN_SCAN;
        } else {
          vulnerabilityDefectConsistencyState =
              VulnerabilityDefectConsistencyState.VULN_OPEN_DEFECT_CLOSED_NEEDS_SCAN;
        }
      }
    }

    vulnerability.setVulnerabilityDefectConsistencyState(vulnerabilityDefectConsistencyState);
    return vulnerabilityDefectConsistencyState;
  }
  /* (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);
  }
示例#7
0
  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;
  }
示例#8
0
  private int getAge(long birthday) {
    Calendar today = Calendar.getInstance();
    Calendar birthDate = Calendar.getInstance();
    birthDate.setTimeInMillis(birthday);
    if (birthDate.after(today)) {
      throw new IllegalArgumentException("Invalid birthday: Can't be born in the future");
    }
    int age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);
    Log.i(
        TAG,
        "birthday year:" + birthDate.get(Calendar.YEAR) + " now year:" + today.get(Calendar.YEAR));
    // If birth date is greater than todays date (after 2 days adjustment of leap year) then
    // decrement age one year
    if ((birthDate.get(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR) > 3)
        || (birthDate.get(Calendar.MONTH) > today.get(Calendar.MONTH))) {
      age--;
      // If birth date and todays date are of same month and birth day of month is greater than
      // todays day of month then decrement age
    } else if ((birthDate.get(Calendar.MONTH) == today.get(Calendar.MONTH))
        && (birthDate.get(Calendar.DAY_OF_MONTH) > today.get(Calendar.DAY_OF_MONTH))) {
      age--;
    }

    return age;
  }
示例#9
0
  /**
   * Re-implementation of the Excel PRICE function (a rather primitive bond price formula). The
   * re-implementation is not exact, because this function does not consider daycount conventions.
   *
   * @param settlementDate Valuation date.
   * @param maturityDate Maturity date of the bond.
   * @param coupon Coupon payment.
   * @param yield Yield (discount factor, using frequency: 1/(1 + yield/frequency).
   * @param redemption Redemption (notional repayment).
   * @param frequency Frequency (1,2,4).
   * @return price Clean price.
   */
  public static double price(
      java.util.Date settlementDate,
      java.util.Date maturityDate,
      double coupon,
      double yield,
      double redemption,
      int frequency) {
    double price = 0.0;

    if (maturityDate.after(settlementDate)) {
      price += redemption;
    }

    Calendar paymentDate = Calendar.getInstance();
    paymentDate.setTime(maturityDate);
    while (paymentDate.after(settlementDate)) {
      price += coupon;

      // Disocunt back
      price /= 1.0 + yield / frequency;
      paymentDate.add(Calendar.MONTH, -12 / frequency);
    }

    Calendar periodEndDate = (Calendar) paymentDate.clone();
    periodEndDate.add(Calendar.MONTH, +12 / frequency);

    // Accrue running period
    double accrualPeriod =
        (paymentDate.getTimeInMillis() - settlementDate.getTime())
            / (periodEndDate.getTimeInMillis() - paymentDate.getTimeInMillis());
    price *= Math.pow(1.0 + yield / frequency, accrualPeriod);
    price -= coupon * accrualPeriod;

    return price;
  }
示例#10
0
  /**
   * 获取两个日期之间的间隔日期
   *
   * @author modi
   * @version 1.0.0
   */
  public static int getDaysBetween(final String beginDate, final String endDate) {

    try {
      final SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.SIMPLIFIED_CHINESE);
      final Date bDate = format.parse(beginDate);
      final Date eDate = format.parse(endDate);
      Calendar d1 = new GregorianCalendar();
      d1.setTime(bDate);
      final Calendar d2 = new GregorianCalendar();
      d2.setTime(eDate);

      if (d1.after(d2)) {
        return 0;
      }

      int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
      final int y2 = d2.get(Calendar.YEAR);
      if (d1.get(Calendar.YEAR) != y2) {
        d1 = (Calendar) d1.clone();
        do {
          days += d1.getActualMaximum(Calendar.DAY_OF_YEAR); // 得到当年的实际天数
          d1.add(Calendar.YEAR, 1);
        } while (d1.get(Calendar.YEAR) != y2);
      }
      return days;
    } catch (ParseException e) {
      return 0;
    }
  }
示例#11
0
  public static int getIntervalMonths(Date date1, Date date2) {
    int iMonth = 0;
    int flag = 0;
    try {
      Calendar objCalendarDate1 = Calendar.getInstance();
      objCalendarDate1.setTime(date1);

      Calendar objCalendarDate2 = Calendar.getInstance();
      objCalendarDate2.setTime(date2);

      if (objCalendarDate2.equals(objCalendarDate1)) return 0;
      if (objCalendarDate1.after(objCalendarDate2)) {
        Calendar temp = objCalendarDate1;
        objCalendarDate1 = objCalendarDate2;
        objCalendarDate2 = temp;
      }
      if (objCalendarDate2.get(Calendar.DAY_OF_MONTH) < objCalendarDate1.get(Calendar.DAY_OF_MONTH))
        flag = 1;

      if (objCalendarDate2.get(Calendar.YEAR) > objCalendarDate1.get(Calendar.YEAR))
        iMonth =
            ((objCalendarDate2.get(Calendar.YEAR) - objCalendarDate1.get(Calendar.YEAR)) * 12
                    + objCalendarDate2.get(Calendar.MONTH)
                    - flag)
                - objCalendarDate1.get(Calendar.MONTH);
      else
        iMonth = objCalendarDate2.get(Calendar.MONTH) - objCalendarDate1.get(Calendar.MONTH) - flag;

    } catch (Exception e) {
      e.printStackTrace();
    }
    return iMonth;
  }
  private void accessBusinessCheck(UploadRequestUrl requestUrl, String password)
      throws BusinessException {
    UploadRequest request = requestUrl.getUploadRequest();
    if (!isValidPassword(requestUrl, password)) {
      throw new BusinessException(
          BusinessErrorCode.UPLOAD_REQUEST_URL_FORBIDDEN,
          "You do not have the right to get this upload request url : " + requestUrl.getUuid());
    }

    if (!(request.getStatus().equals(UploadRequestStatus.STATUS_ENABLED)
        || request.getStatus().equals(UploadRequestStatus.STATUS_CLOSED))) {
      throw new BusinessException(
          BusinessErrorCode.UPLOAD_REQUEST_READONLY_MODE,
          "The current upload request url is not available : " + requestUrl.getUuid());
    }

    Calendar now = GregorianCalendar.getInstance();
    Calendar compare = GregorianCalendar.getInstance();
    compare.setTime(request.getActivationDate());
    if (now.before(compare)) {
      throw new BusinessException(
          BusinessErrorCode.UPLOAD_REQUEST_NOT_ENABLE_YET,
          "The current upload request url is not enable yet : " + requestUrl.getUuid());
    }
    compare.setTime(request.getExpiryDate());
    if (now.after(compare)) {
      throw new BusinessException(
          BusinessErrorCode.UPLOAD_REQUEST_NOT_ENABLE_YET,
          "The current upload request url is no more available now. : " + requestUrl.getUuid());
    }
  }
示例#13
0
 public Calendar addRecurring(Calendar c) {
   Calendar now = new GregorianCalendar();
   if (isExact()) {
     c = now;
   }
   now.set(Calendar.SECOND, 0);
   now.add(Calendar.MINUTE, -1);
   List<Integer> weekdays = getWeekdays();
   if (weekdays.size() == 0) {
     if ((getStartDate() == null || (getStartDate() != null && now.after(getStartDate())))
         && (getEndDate() == null || (getEndDate() != null && now.before((getEndDate()))))) {
       do {
         c.add(Calendar.DAY_OF_MONTH, getDays());
         c.add(Calendar.MONTH, getMonths());
         c.add(Calendar.YEAR, getYears());
         if (!isForDue()) {
           c.add(Calendar.MINUTE, getMinutes());
           c.add(Calendar.HOUR, getHours());
         }
       } while (c.before(now));
     }
   } else {
     int diff = 8;
     if (c.compareTo(now) < 0) c = now;
     c.add(Calendar.DAY_OF_MONTH, 1);
     for (Integer day : weekdays) {
       int local_diff = day - c.get(Calendar.DAY_OF_WEEK);
       if (local_diff < 0) local_diff += 7;
       if (diff > local_diff) diff = local_diff;
     }
     c.add(Calendar.DAY_OF_MONTH, diff);
   }
   return c;
 }
示例#14
0
  /**
   * Method getMonthsArray. Get a list of months which represents each element by Calendar object
   *
   * @param nMonth
   * @param nYear
   * @return ArrayList
   */
  public ArrayList getMonthsArray(int nFromMonth, int nFromYear, int nToMonth, int nToYear)
      throws Exception {
    ArrayList alsMonths = new ArrayList();
    try {
      Calendar calFrom = Calendar.getInstance();
      Calendar calTo = Calendar.getInstance();

      calFrom.set(nFromYear, nFromMonth - 1, 1);
      // Get the last day of ToMonth
      calTo.set(nToYear, nToMonth - 1, 1);

      // Get milliseconds from 1-Jan-1970
      long nFromMs = calFrom.getTime().getTime();
      long nToMs = calTo.getTime().getTime();
      // To date is lower than From date
      if (nToMs < nFromMs) {
        return alsMonths;
      }
      // Generate list of weeks represents in SUNDAYs list (may) except first week
      while (!calFrom.after(calTo)) {
        alsMonths.add(calFrom.clone());
        calFrom.add(Calendar.MONTH, 1);
      }
    } catch (Exception e) {
    }

    return alsMonths;
  }
示例#15
0
  /**
   * Fix and update all alarm instance when a time change event occurs.
   *
   * @param context application context
   */
  public static void fixAlarmInstances(Context context) {
    // Register all instances after major time changes or when phone restarts
    final ContentResolver contentResolver = context.getContentResolver();
    final Calendar currentTime = getCurrentTime();
    for (AlarmInstance instance : AlarmInstance.getInstances(contentResolver, null)) {
      final Alarm alarm = Alarm.getAlarm(contentResolver, instance.mAlarmId);
      final Calendar priorAlarmTime = alarm.getPreviousAlarmTime(instance.getAlarmTime());
      final Calendar missedTTLTime = instance.getMissedTimeToLive();
      if (currentTime.before(priorAlarmTime) || currentTime.after(missedTTLTime)) {
        final Calendar oldAlarmTime = instance.getAlarmTime();
        final Calendar newAlarmTime = alarm.getNextAlarmTime(currentTime);
        final CharSequence oldTime = DateFormat.format("MM/dd/yyyy hh:mm a", oldAlarmTime);
        final CharSequence newTime = DateFormat.format("MM/dd/yyyy hh:mm a", newAlarmTime);
        LogUtils.i(
            "A time change has caused an existing alarm scheduled to fire at %s to"
                + " be replaced by a new alarm scheduled to fire at %s",
            oldTime, newTime);

        // The time change is so dramatic the AlarmInstance doesn't make any sense;
        // remove it and schedule the new appropriate instance.
        AlarmStateManager.setDismissState(context, instance);
      } else {
        registerInstance(context, instance, false);
      }
    }

    updateNextAlarm(context);
  }
示例#16
0
 /**
  * 获取工作日
  *
  * @param d1
  * @param d2
  * @return
  */
 public int getWorkingDay(java.util.Calendar d1, java.util.Calendar d2) {
   int result = -1;
   if (d1.after(d2)) { // swap dates so that d1 is start and d2 is end
     java.util.Calendar swap = d1;
     d1 = d2;
     d2 = swap;
   }
   // int betweendays = getDaysBetween(d1, d2);
   // int charge_date = 0;
   int charge_start_date = 0; // 开始日期的日期偏移量
   int charge_end_date = 0; // 结束日期的日期偏移量
   // 日期不在同一个日期内
   int stmp;
   int etmp;
   stmp = 7 - d1.get(Calendar.DAY_OF_WEEK);
   etmp = 7 - d2.get(Calendar.DAY_OF_WEEK);
   if (stmp != 0 && stmp != 6) { // 开始日期为星期六和星期日时偏移量为0
     charge_start_date = stmp - 1;
   }
   if (etmp != 0 && etmp != 6) { // 结束日期为星期六和星期日时偏移量为0
     charge_end_date = etmp - 1;
   }
   // }
   result =
       (getDaysBetween(this.getNextMonday(d1), this.getNextMonday(d2)) / 7) * 5
           + charge_start_date
           - charge_end_date;
   // System.out.println("charge_start_date>" + charge_start_date);
   // System.out.println("charge_end_date>" + charge_end_date);
   // System.out.println("between day is-->" + betweendays);
   return result;
 }
  @Override
  public void validate(final Object object, final Errors errors) {
    final PaymentDetailsForm form = (PaymentDetailsForm) object;

    final Calendar start = parseDate(form.getStartMonth(), form.getStartYear());
    final Calendar expiration = parseDate(form.getExpiryMonth(), form.getExpiryYear());

    if (start != null && expiration != null && start.after(expiration)) {
      errors.rejectValue("startMonth", "payment.startDate.invalid");
    }

    final boolean editMode = StringUtils.isNotBlank(form.getPaymentId());
    if (editMode || Boolean.TRUE.equals(form.getNewBillingAddress())) {
      ValidationUtils.rejectIfEmptyOrWhitespace(
          errors, "billingAddress.titleCode", "address.title.invalid");
      ValidationUtils.rejectIfEmptyOrWhitespace(
          errors, "billingAddress.firstName", "address.firstName.invalid");
      ValidationUtils.rejectIfEmptyOrWhitespace(
          errors, "billingAddress.lastName", "address.lastName.invalid");
      ValidationUtils.rejectIfEmptyOrWhitespace(
          errors, "billingAddress.line1", "address.line1.invalid");
      ValidationUtils.rejectIfEmptyOrWhitespace(
          errors, "billingAddress.townCity", "address.townCity.invalid");
      ValidationUtils.rejectIfEmptyOrWhitespace(
          errors, "billingAddress.postcode", "address.postcode.invalid");
      ValidationUtils.rejectIfEmptyOrWhitespace(
          errors, "billingAddress.countryIso", "address.country.invalid");
      // ValidationUtils.rejectIfEmptyOrWhitespace(errors, "billingAddress.line2",
      // "address.line2.invalid"); // for some addresses this field is required by cybersource
    }
  }
 public int compare(Object x, Object y) {
   Calendar xcal = (Calendar) x;
   Calendar ycal = (Calendar) y;
   if (xcal.before(ycal)) return -1;
   if (xcal.after(ycal)) return 1;
   return 0;
 }
示例#19
0
  public static boolean checkDate(String date1, String date2) {

    Date date11 = DateUtil.str2Date(date1, "yyyy-MM-dd HH:mm:ss"); // 起始时间

    Date date22 = DateUtil.str2Date(date2, "yyyy-MM-dd HH:mm:ss"); // 终止时间

    Calendar scalendar = Calendar.getInstance();
    scalendar.setTime(date11); // 起始时间

    Calendar ecalendar = Calendar.getInstance();
    ecalendar.setTime(date22); // 终止时间

    Calendar calendarnow = Calendar.getInstance();

    System.out.println(date11.toString());
    System.out.println(date22.toString());
    System.out.println(scalendar.toString());
    System.out.println(ecalendar.toString());
    System.out.println(calendarnow.toString());

    if (calendarnow.after(scalendar) && calendarnow.before(ecalendar)) {
      return true;
    } else {
      return false;
    }
  }
  private boolean valid() {
    boolean valid = true;
    String errorMessage = "";

    if (start == null || end == null) {
      errorMessage += "Missing Dates\n".toUpperCase();
      valid = false;
    } else {
      if (start.after(end)) {
        errorMessage += "Drop off Date Must be After Pick Up Date\n".toUpperCase();
        valid = false;
      }
    }
    if (customers.getSelectedItem().toString().equals("SELECT A CUSTOMER")) {
      errorMessage += "Select a Customer\n".toUpperCase();
      valid = false;
    }
    if (vehicles.getSelectedItem().toString().equals("SELECT A VEHICLE")) {
      errorMessage += "Select a Vehicle\n".toUpperCase();
      valid = false;
    }

    if (!valid) ApplicationHelper.toastShort(getApplicationContext(), "ERRORS\n" + errorMessage);

    return valid;
  }
示例#21
0
 /**
  * ************************************************************************ Function: public
  * static boolean IsAfterToday(int day, int month, int year) Description: returns true if the date
  * passed as parameter with format (int day, int month, int year) is AFTER today's date.
  * Parameters: - day[in]: input date - month[in]: input month - year[in]: input year Return:
  * boolean. Author: Duong Thanh Nhan Created date: 2001
  * ************************************************************************
  */
 public static boolean IsAfterToday(int day, int month, int year) {
   java.util.Calendar today = java.util.Calendar.getInstance();
   java.util.Calendar dt = java.util.Calendar.getInstance();
   dt.set(year, month, day);
   if (dt.after(today)) return true;
   return false;
 } // IsAfterToday
 public int addFutureMeeting(Set<Contact> contacts, Calendar date) {
   /**
    * @param currentDate an instance of Calendar to get the current date in order to see if the
    *     date provided is valid
    */
   Calendar currentDate = GregorianCalendar.getInstance();
   if (currentDate.after(date)) // i.e if date param is in the past
   {
     throw new IllegalArgumentException("Specified date is in the past! Please try again.");
   }
   for (Iterator<Contact> itr = contacts.iterator(); itr.hasNext(); ) {
     if (!contactSet.contains(itr.next())) // if contactSet does NOT contain itr.next()
     {
       throw new IllegalArgumentException(
           "Contact \"" + itr.next().getName() + "\" does not exist! Please try again.");
     }
   }
   /** if neither exception thrown, FutureMeeting object can be instantiated */
   FutureMeeting tmp = new FutureMeetingImpl(meetingIdAssigner(), contacts, date);
   meetingSet.add(tmp);
   futureMeetings.add(tmp);
   System.out.println("Success - Meeting Scheduled!");
   /** @return the ID for the meeting by calling the getId() method of FutureMeetingImpl */
   return tmp.getId();
 }
  public void setReenterTime(InstanceWorld world) {
    if (world instanceof DPFWorld) {
      // Reenter time should be cleared every Wed and Sat at 6:30 AM, so we set next suitable
      Calendar reenter;
      Calendar now = Calendar.getInstance();
      Calendar reenterPointWed = (Calendar) now.clone();
      reenterPointWed.set(Calendar.AM_PM, Calendar.AM);
      reenterPointWed.set(Calendar.MINUTE, RESET_MIN);
      reenterPointWed.set(Calendar.HOUR_OF_DAY, RESET_HOUR);
      reenterPointWed.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
      Calendar reenterPointSat = (Calendar) reenterPointWed.clone();
      reenterPointSat.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);

      if (now.after(reenterPointSat)) {
        reenterPointWed.add(Calendar.WEEK_OF_MONTH, 1);
        reenter = (Calendar) reenterPointWed.clone();
      } else {
        reenter = (Calendar) reenterPointSat.clone();
      }

      SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.INSTANT_ZONE_S1_RESTRICTED);
      sm.addInstanceName(world.getTemplateId());
      // set instance reenter time for all allowed players
      for (int objectId : world.getAllowed()) {
        L2PcInstance player = L2World.getInstance().getPlayer(objectId);
        if ((player != null) && player.isOnline()) {
          InstanceManager.getInstance()
              .setInstanceTime(objectId, world.getTemplateId(), reenter.getTimeInMillis());
          player.sendPacket(sm);
        }
      }
    }
  }
  // @Test
  public void testEveryMinuteEveryHourEveryDay() {
    ScheduleExpression everyMinEveryHourEveryDay = this.getTimezoneSpecificScheduleExpression();
    everyMinEveryHourEveryDay.minute("*");
    everyMinEveryHourEveryDay.hour("*");

    CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(everyMinEveryHourEveryDay);

    Calendar firstTimeout = calendarTimeout.getFirstTimeout();
    Calendar previousTimeout = firstTimeout;
    for (int i = 1; i <= 65; i++) {
      Calendar nextTimeout = calendarTimeout.getNextTimeout(previousTimeout);

      Assert.assertNotNull(timeZoneDisplayName, nextTimeout);
      Assert.assertNotNull(timeZoneDisplayName, nextTimeout.after(previousTimeout));
      //            logger.debug("First timeout was: " + firstTimeout.getTime() + " Previous timeout
      // was: "
      //                    + previousTimeout.getTime() + " Next timeout is " +
      // nextTimeout.getTime());
      long diff = nextTimeout.getTimeInMillis() - previousTimeout.getTimeInMillis();
      long diffWithFirstTimeout = nextTimeout.getTimeInMillis() - firstTimeout.getTimeInMillis();
      Assert.assertEquals(timeZoneDisplayName, 60 * 1000, diff);
      Assert.assertEquals(timeZoneDisplayName, 60 * 1000 * i, diffWithFirstTimeout);

      previousTimeout = nextTimeout;
    }
  }
示例#25
0
  public int findAllBirthsBetweenIntervalByGender(Calendar startDate, Calendar endDate, int flag) {

    int count = 0;
    List<PregnancyOutcome> outcomes = genericDao.findAll(PregnancyOutcome.class, true);

    for (PregnancyOutcome outcome : outcomes) {
      Calendar outcomeDate = outcome.getOutcomeDate();
      if ((outcomeDate.after(startDate) || outcomeDate.equals(startDate))
          && (outcomeDate.before(endDate))) {

        List<Outcome> allOutcomes = outcome.getOutcomes();
        for (Outcome o : allOutcomes) {
          if (o.getType().equals(siteProperties.getLiveBirthCode())) {
            // male
            if (flag == 0) {
              if (o.getChild().getGender().equals(siteProperties.getMaleCode())) {
                if (o.getType().equals(siteProperties.getLiveBirthCode())) {
                  count++;
                }
              }
            }
            // female
            else {
              if (o.getChild().getGender().equals(siteProperties.getFemaleCode())) {
                if (o.getType().equals(siteProperties.getLiveBirthCode())) {
                  count++;
                }
              }
            }
          }
        }
      }
    }
    return count;
  }
示例#26
0
  @RequestMapping(value = "/show", method = RequestMethod.POST)
  public ModelAndView show(@ModelAttribute ReportForm reportForm) {
    // always from the first day
    Calendar calendarFrom =
        new GregorianCalendar(reportForm.getFromYear(), reportForm.getFromMonth(), 1);
    Calendar calendarUntil =
        new GregorianCalendar(reportForm.getUntilYear(), reportForm.getUntilMonth(), 1);

    // input trasverse are also supported
    Date from, until;
    if (calendarFrom.after(calendarUntil)) {
      from = calendarUntil.getTime();
      until = calendarFrom.getTime();
    } else {
      from = calendarFrom.getTime();
      until = calendarUntil.getTime();
    }

    Report report =
        reportService.generate(
            UserServiceFactory.getUserService().getCurrentUser().getEmail(),
            UserServiceFactory.getUserService().getCurrentUser().getNickname(),
            from,
            until);
    return new ModelAndView().addObject("report", report).addObject("mailerService", mailerService);
  }
示例#27
0
 public static boolean checkDateRanges(String fromDate, String toDate) {
   try {
     Date parsedDate = CoreApiServiceLocator.getDateTimeService().convertToDate(fromDate.trim());
     Calendar fromCalendar = Calendar.getInstance();
     fromCalendar.setLenient(false);
     fromCalendar.setTime(parsedDate);
     fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
     fromCalendar.set(Calendar.MINUTE, 0);
     fromCalendar.set(Calendar.SECOND, 0);
     fromCalendar.set(Calendar.MILLISECOND, 0);
     parsedDate = CoreApiServiceLocator.getDateTimeService().convertToDate(toDate.trim());
     Calendar toCalendar = Calendar.getInstance();
     toCalendar.setLenient(false);
     toCalendar.setTime(parsedDate);
     toCalendar.set(Calendar.HOUR_OF_DAY, 0);
     toCalendar.set(Calendar.MINUTE, 0);
     toCalendar.set(Calendar.SECOND, 0);
     toCalendar.set(Calendar.MILLISECOND, 0);
     if (fromCalendar.after(toCalendar)) {
       return false;
     }
     return true;
   } catch (Exception ex) {
     return false;
   }
 }
示例#28
0
  public static boolean date1GreaterThanDate2(Date date1, Date date2) {
    boolean isEqual = false;

    Calendar cal1 = Calendar.getInstance();
    cal1.setTime(date1);
    cal1.set(Calendar.HOUR, 0);
    cal1.set(Calendar.MINUTE, 0);
    cal1.set(Calendar.SECOND, 0);
    cal1.set(Calendar.MILLISECOND, 0);

    Calendar cal2 = Calendar.getInstance();
    cal2.setTime(date2);
    cal2.set(Calendar.HOUR, 0);
    cal2.set(Calendar.MINUTE, 0);
    cal2.set(Calendar.SECOND, 0);
    cal2.set(Calendar.MILLISECOND, 0);

    if (cal1.after(cal2)) {
      isEqual = true;
    } else if (cal1.before(cal2)) {
      isEqual = false;
    }

    return isEqual;
  }
 public void run() {
   LOG.debug("run: " + this);
   Calendar now = Calendar.getInstance();
   Calendar start = this.getStartCalendar();
   Calendar end = this.getEndCalendar();
   if (now.after(end)) {
     this.setStatus(Status.SENT);
     this.stopReminder();
     this.refreshReminder();
   } else if ((now.equals(start) || now.after(start))
       && now.get(Calendar.MINUTE) == start.get(Calendar.MINUTE)
       && now.get(Calendar.HOUR_OF_DAY) == start.get(Calendar.HOUR_OF_DAY)
       && Arrays.asList(WEEKDAYS).contains(now.get(Calendar.DAY_OF_WEEK))) {
     this.sendReminder();
   }
 }
  @Test
  public void testEveryMinuteEveryHourEveryDay() {
    ScheduleExpression everyMinEveryHourEveryDay = new ScheduleExpression();
    everyMinEveryHourEveryDay.minute("*");
    everyMinEveryHourEveryDay.hour("*");

    CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(everyMinEveryHourEveryDay);

    Calendar firstTimeout = calendarTimeout.getFirstTimeout();
    Calendar previousTimeout = firstTimeout;
    for (int i = 1; i <= 65; i++) {
      Calendar nextTimeout = calendarTimeout.getNextTimeout(previousTimeout);

      Assert.assertNotNull("Next timeout is null", nextTimeout);
      Assert.assertNotNull(
          "Next timeout is *before* the current time", nextTimeout.after(previousTimeout));
      System.out.println(
          "First timeout was: "
              + firstTimeout.getTime()
              + " Previous timeout was: "
              + previousTimeout.getTime()
              + " Next timeout is "
              + nextTimeout.getTime());
      long diff = nextTimeout.getTimeInMillis() - previousTimeout.getTimeInMillis();
      long diffWithFirstTimeout = nextTimeout.getTimeInMillis() - firstTimeout.getTimeInMillis();
      Assert.assertEquals("Unexpected timeout value: " + nextTimeout, 60 * 1000, diff);
      Assert.assertEquals(
          "Unexpected timeout value when compared to first timeout: " + nextTimeout.getTime(),
          60 * 1000 * i,
          diffWithFirstTimeout);

      previousTimeout = nextTimeout;
    }
  }