List of usage examples for java.util Calendar before
public boolean before(Object when)
Calendar
represents a time before the time represented by the specified Object
. From source file:com.wkb.core.util.IdcardUtils.java
/** * ??/*from w ww .j a v a 2 s .c o m*/ * * @param idCard * ?? * @param minAge * ? * @param minType * ???145 * @param maxAge * * @param maxType * ??145 * @return ? */ public static boolean valiAge(String idCard, int minAge, byte minType, int maxAge, byte maxType) { //?? if (!validateCard(idCard)) return false; if (idCard.length() == CHINA_ID_MIN_LENGTH) { idCard = conver15CardTo18(idCard); } //? Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); //? Calendar birthCal = Calendar.getInstance(); String birth = idCard.substring(6, 14); Date birthDate = null; try { birthDate = sdf.parse(birth); } catch (ParseException e) { e.printStackTrace(); } birthCal.setTime(birthDate); if (Constant.COMMON.DAY == minType) { birthCal.add(Calendar.DATE, minAge); } else if (Constant.COMMON.MONTH == minType) { birthCal.add(Calendar.MONTH, minAge); } else { // birthCal.add(Calendar.YEAR, minAge); } if (cal.before(birthCal)) { return false; } //maxAge0? if (maxAge == 0) { return true; } birthCal.setTime(birthDate); if (Constant.COMMON.DAY == maxType) { birthCal.add(Calendar.DATE, maxAge + 1); } else if (Constant.COMMON.MONTH == maxType) { birthCal.add(Calendar.MONTH, maxAge + 1); } else { // birthCal.add(Calendar.YEAR, maxAge + 1); } if (!cal.before(birthCal)) return false; return true; }
From source file:lineage2.gameserver.network.telnet.commands.TelnetServer.java
/** * Constructor for TelnetServer.//from w w w . j av a 2s. com */ public TelnetServer() { _commands.add(new TelnetCommand("version", "ver") { @Override public String getUsage() { return "version"; } @Override public String handle(String[] args) { return "Rev." + GameServer.getInstance().getVersion().getRevisionNumber() + " Builded : " + GameServer.getInstance().getVersion().getBuildDate() + "\n"; } }); _commands.add(new TelnetCommand("uptime") { @Override public String getUsage() { return "uptime"; } @Override public String handle(String[] args) { return DurationFormatUtils.formatDurationHMS(ManagementFactory.getRuntimeMXBean().getUptime()) + "\n"; } }); _commands.add(new TelnetCommand("restart") { @Override public String getUsage() { return "restart <seconds>|now>"; } @Override public String handle(String[] args) { if (args.length == 0) { return null; } StringBuilder sb = new StringBuilder(); if (NumberUtils.isNumber(args[0])) { int val = NumberUtils.toInt(args[0]); Shutdown.getInstance().schedule(val, Shutdown.RESTART); sb.append("Server will restart in ").append(Shutdown.getInstance().getSeconds()) .append(" seconds!\n"); sb.append("Type \"abort\" to abort restart!\n"); } else if (args[0].equalsIgnoreCase("now")) { sb.append("Server will restart now!\n"); Shutdown.getInstance().schedule(0, Shutdown.RESTART); } else { String[] hhmm = args[0].split(":"); Calendar date = Calendar.getInstance(); Calendar now = Calendar.getInstance(); date.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hhmm[0])); date.set(Calendar.MINUTE, hhmm.length > 1 ? Integer.parseInt(hhmm[1]) : 0); date.set(Calendar.SECOND, 0); date.set(Calendar.MILLISECOND, 0); if (date.before(now)) { date.roll(Calendar.DAY_OF_MONTH, true); } int seconds = (int) ((date.getTimeInMillis() / 1000L) - (now.getTimeInMillis() / 1000L)); Shutdown.getInstance().schedule(seconds, Shutdown.RESTART); sb.append("Server will restart in ").append(Shutdown.getInstance().getSeconds()) .append(" seconds!\n"); sb.append("Type \"abort\" to abort restart!\n"); } return sb.toString(); } }); _commands.add(new TelnetCommand("shutdown") { @Override public String getUsage() { return "shutdown <seconds>|now|<hh:mm>"; } @Override public String handle(String[] args) { if (args.length == 0) { return null; } StringBuilder sb = new StringBuilder(); if (NumberUtils.isNumber(args[0])) { int val = NumberUtils.toInt(args[0]); Shutdown.getInstance().schedule(val, Shutdown.SHUTDOWN); sb.append("Server will shutdown in ").append(Shutdown.getInstance().getSeconds()) .append(" seconds!\n"); sb.append("Type \"abort\" to abort shutdown!\n"); } else if (args[0].equalsIgnoreCase("now")) { sb.append("Server will shutdown now!\n"); Shutdown.getInstance().schedule(0, Shutdown.SHUTDOWN); } else { String[] hhmm = args[0].split(":"); Calendar date = Calendar.getInstance(); Calendar now = Calendar.getInstance(); date.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hhmm[0])); date.set(Calendar.MINUTE, hhmm.length > 1 ? Integer.parseInt(hhmm[1]) : 0); date.set(Calendar.SECOND, 0); date.set(Calendar.MILLISECOND, 0); if (date.before(now)) { date.roll(Calendar.DAY_OF_MONTH, true); } int seconds = (int) ((date.getTimeInMillis() / 1000L) - (now.getTimeInMillis() / 1000L)); Shutdown.getInstance().schedule(seconds, Shutdown.SHUTDOWN); sb.append("Server will shutdown in ").append(Shutdown.getInstance().getSeconds()) .append(" seconds!\n"); sb.append("Type \"abort\" to abort shutdown!\n"); } return sb.toString(); } }); _commands.add(new TelnetCommand("abort") { @Override public String getUsage() { return "abort"; } @Override public String handle(String[] args) { Shutdown.getInstance().cancel(); return "Aborted.\n"; } }); }
From source file:com.vaquerosisd.projectmanager.NewProject.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_project); getActionBar().setDisplayHomeAsUpEnabled(true); //Initialize database operation object db = new ProjectOperations(this); db.open();/*ww w . j av a 2 s .co m*/ //Initialize file operations instance fO = new FileOperations(this); //UI handlers references final EditText projectNameEditText = (EditText) findViewById(R.id.newProject_ProjectName); final EditText startDateEditText = (EditText) findViewById(R.id.newProject_StartDate); final EditText dueDateEditText = (EditText) findViewById(R.id.newProject_DueDate); statusSpinner = (Spinner) findViewById(R.id.newProject_StatusSpinner); final Button addProjectButton = (Button) findViewById(R.id.addProject); //Set spinner String statusItemsString = "New\nIn progress\nPrinting\nOn hold\nCancelled\nReviewing\nDelegated\nCompleted\n"; fO.createStringFile(statusFileName, statusItemsString); setStatusSpinner(); int statusPosition = statusSpinnerAdapter.getPosition("New"); statusSpinner.setSelection(statusPosition, true); //Check if custom option is selected to open a dialog to provide a custom status statusSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if ("Custom...".equals((String) statusSpinnerAdapter.getItem(position))) { DialogFragment customStatusDialog = new CustomStatus(); customStatusDialog.show(getFragmentManager(), "Custom Status Dialog"); } } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); //StartDate click listener startDateEditText.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { showDatePickerDialog(arg0, STARTDATE_DIALOG_TAG, startDateEditText, startDateStrings); } }); //DueDate click listener dueDateEditText.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { showDatePickerDialog(arg0, DUEDATE_DIALOG_TAG, dueDateEditText, dueDateStrings); } }); //Add project to database addProjectButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //Get EditText info String projectNameString = projectNameEditText.getText().toString(); String projectStatusString = statusSpinner.getSelectedItem().toString(); String projectStartDateString = startDateEditText.getText().toString(); String projectDueDateString = dueDateEditText.getText().toString(); //Add project to database if all input elements are filled boolean dueDateBeforeStartDate = true; Calendar startDateCalendar = Calendar.getInstance(); startDateCalendar.set(startDateStrings[0], startDateStrings[1], startDateStrings[2]); Calendar dueDateCalendar = Calendar.getInstance(); dueDateCalendar.set(dueDateStrings[0], dueDateStrings[1], dueDateStrings[2]); if (startDateCalendar.before(dueDateCalendar) || startDateCalendar.equals(dueDateCalendar)) dueDateBeforeStartDate = false; if (dueDateBeforeStartDate) { Toast.makeText(getApplicationContext(), R.string.dueDateError, Toast.LENGTH_LONG).show(); return; } else if (!projectNameString.equals("") && !projectStartDateString.equals("") && !projectDueDateString.equals("")) { File contentDir = new File("/storage/sdcard0/ProjectManager/" + projectNameString); contentDir.mkdirs(); db.addProject(projectNameString, projectStatusString, startDateStrings, dueDateStrings, contentDir.getAbsolutePath()); Toast.makeText(getApplicationContext(), R.string.projectAdded, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), R.string.incomplete, Toast.LENGTH_LONG).show(); return; } //Inform of successful adding Intent intent = new Intent(); setResult(RESULT_OK, intent); finish(); } }); }
From source file:nl.strohalm.cyclos.utils.tasks.HazelcastTaskRunner.java
@Override protected void doRunScheduledTask(final String taskName, final Calendar time) { // Scheduled tasks won't run twice for the same hour in the entire cluster. LockKey lockKey = new LockKey(KeyType.SCHEDULED_TASK, taskName); ILock lock = hazelcastInstance.getLock(lockKey); if (lock.tryLock()) { // No other node is trying to execute this scheduled task try {// w ww .j a v a 2 s . c o m // Determine whether the task is daily ScheduledTask scheduledTask = getSchedulingHandler().getTask(taskName); boolean daily = !scheduledTask.isEveryHour(); int field = daily ? Calendar.DAY_OF_MONTH : Calendar.HOUR_OF_DAY; // Check the last hour this task was performed Calendar lastRun = scheduledTaskControl.get(taskName); if (lastRun != null) { lastRun = DateUtils.truncate(lastRun, field); } Calendar thisRun = DateUtils.truncate(time, field); // Fill all the gaps between the last run and this run. // In normal execution, this loop will be evaluated only once. while (lastRun == null || lastRun.before(thisRun)) { if (lastRun == null) { // Never executed: run as this time lastRun = thisRun; } else { // Increment the field (either hour or day) lastRun.add(field, 1); } // Run the task super.doRunScheduledTask(taskName, lastRun); // Store the task hour, no other node will run it on this hour again scheduledTaskControl.put(taskName, lastRun); } } finally { HazelcastHelper.release(lock); } } }
From source file:com.mb.framework.util.DateTimeUtil.java
/** * /*w ww .j av a 2 s . c o m*/ * This method is used to check whether the date is before current Date. * * @param dt * @return */ public static boolean isDateExpired(String dt) { boolean isExpired = false; Calendar expDt = Calendar.getInstance(); expDt.setTimeInMillis(Long.valueOf(dt)); Calendar today = Calendar.getInstance(); if (expDt.before(today)) { isExpired = true; } return isExpired; }
From source file:TimeSpan.java
/** * Returns {@code true} if the end date occurs after the start date during * the period of time represented by this time span. * // w w w.j av a 2s.c o m * @param mutableStartDate a <i>mutable<i> {@code Calendar} object that will * be changed to the ending time of this time range as a side effect * of this method */ private boolean isInRange(Calendar mutableStartDate, Calendar endDate) { // ensure that the ending date does not occur before the time span would // have started if (endDate.before(mutableStartDate)) return false; // update the start date to be the date at the end of the time span Calendar tsEnd = mutableStartDate; tsEnd.add(Calendar.YEAR, years); tsEnd.add(Calendar.MONTH, months); tsEnd.add(Calendar.WEEK_OF_YEAR, weeks); tsEnd.add(Calendar.DAY_OF_YEAR, days); tsEnd.add(Calendar.HOUR, hours); return endDate.before(tsEnd); }
From source file:org.kalypso.model.hydrology.operation.evaporation.AbstractEvaporationCalculator.java
private IStatus calculateEvaporation(final IProgressMonitor monitor) { final IStatusCollector stati = new StatusCollector(ModelNA.PLUGIN_ID); final Calendar to = CalendarUtilities.getCalendar(getDateRange().getTo(), KalypsoCorePlugin.getDefault().getTimeZone()); final Calendar ptr = CalendarUtilities.getCalendar(getDateRange().getFrom(), KalypsoCorePlugin.getDefault().getTimeZone()); ptr.set(Calendar.HOUR_OF_DAY, 12); ptr.set(Calendar.MINUTE, 0);//from ww w.j av a 2s. c o m ptr.set(Calendar.SECOND, 0); ptr.set(Calendar.MILLISECOND, 0); // iterate over values inherit the given date range while (ptr.before(to) || DateUtils.isSameDay(ptr, to)) { final Double humidity = getValue( getDataSet(getHumidity(), ptr, ITimeseriesConstants.TYPE_MEAN_HUMIDITY)); final Double sunshine = getValue( getDataSet(getSunshine(), ptr, ITimeseriesConstants.TYPE_SUNSHINE_HOURS)); final Double temperature = getValue( getDataSet(getTemperature(), ptr, ITimeseriesConstants.TYPE_MEAN_TEMPERATURE)); final Double windVelocity = getValue( getDataSet(getWindVelocity(), ptr, ITimeseriesConstants.TYPE_MEAN_WIND_VELOCITY)); if (Doubles.isNaN(humidity, sunshine, temperature, windVelocity)) { final SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); //$NON-NLS-1$ sdf.setTimeZone(KalypsoCorePlugin.getDefault().getTimeZone()); final String msg = String.format(Messages.getString("AbstractEvaporationCalculator_2"), // //$NON-NLS-1$ sdf.format(ptr.getTime()), // Objects.firstNonNull(humidity, Double.NaN), // Objects.firstNonNull(sunshine, Double.NaN), // Objects.firstNonNull(temperature, Double.NaN), // Objects.firstNonNull(windVelocity, Double.NaN)); stati.add(IStatus.WARNING, msg); } else { final Double evaporation = doCalculate(humidity, sunshine, temperature, windVelocity, ptr); if (Objects.isNotNull(evaporation)) addResult(ptr.getTime(), evaporation); } ptr.add(Calendar.DAY_OF_MONTH, 1); } monitor.done(); return stati.asMultiStatus(Messages.getString("AbstractEvaporationCalculator_3")); //$NON-NLS-1$ }
From source file:com.sean.takeastand.storage.ScheduleEditor.java
public void editActivated(AlarmSchedule alarmSchedule) { int UID = alarmSchedule.getUID(); scheduleDatabaseAdapter.updateActivated(UID, alarmSchedule.getActivated()); FixedAlarmSchedule fixedAlarmSchedule = new FixedAlarmSchedule(alarmSchedule); if (alarmSchedule.getActivated()) { Calendar startTime = alarmSchedule.getStartTime(); Calendar endTime = alarmSchedule.getEndTime(); setDailyRepeatingAlarm(UID, Utils.calendarToTimeString(startTime)); Calendar rightNow = Calendar.getInstance(); boolean today = Utils.isTodayActivated(alarmSchedule); //Check to see if need to start a repeating alarm now if (today && startTime.before(rightNow) && endTime.after(rightNow)) { new ScheduledRepeatingAlarm(mContext, fixedAlarmSchedule).setRepeatingAlarm(); Utils.setImageStatus(mContext, Constants.SCHEDULE_RUNNING); }/* w ww .jav a 2 s . c o m*/ } else { cancelDailyRepeatingAlarm(UID); if (UID == Utils.getRunningScheduledAlarm(mContext)) { new ScheduledRepeatingAlarm(mContext, fixedAlarmSchedule).cancelAlarm(); } } }
From source file:com.epam.training.storefront.forms.validation.PaymentDetailsValidator.java
@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()); final Calendar current = Calendar.getInstance(); if (start != null) { if (start.after(current)) { errors.rejectValue("startMonth", "payment.startDate.past.invalid"); }/*www . j a v a 2 s . co m*/ if (expiration != null) { if (start.after(expiration)) { errors.rejectValue("startMonth", "payment.startDate.invalid"); } } } if (expiration != null) { if (expiration.before(current)) { errors.rejectValue("expiryMonth", "payment.expiryDate.future.invalid"); } } final boolean editMode = StringUtils.isNotBlank(form.getPaymentId()); if (editMode || Boolean.TRUE.equals(form.getNewBillingAddress())) { 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"); } }
From source file:com.epam.training.storefront.forms.validation.SbgSopPaymentDetailsValidator.java
@Override public void validate(final Object object, final Errors errors) { final SopPaymentDetailsForm form = (SopPaymentDetailsForm) object; final Calendar start = parseDate(form.getStartMonth(), form.getStartYear()); final Calendar expiration = parseDate(form.getExpiryMonth(), form.getExpiryYear()); final Calendar current = Calendar.getInstance(); if (start != null) { if (start.after(current)) { errors.rejectValue("startMonth", "payment.startDate.past.invalid"); }//from w w w . j av a 2 s . c o m if (expiration != null) { if (start.after(expiration)) { errors.rejectValue("startMonth", "payment.startDate.invalid"); } } } if (expiration != null) { if (expiration.before(current)) { errors.rejectValue("expiryMonth", "payment.expiryDate.future.invalid"); } } if (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"); } }