Example usage for java.util Calendar before

List of usage examples for java.util Calendar before

Introduction

In this page you can find the example usage for java.util Calendar before.

Prototype

public boolean before(Object when) 

Source Link

Document

Returns whether this Calendar represents a time before the time represented by the specified Object.

Usage

From source file:com.arellomobile.android.push.PushManager.java

private boolean neededToRequestPushWooshServer(Context context) {
    Calendar nowTime = Calendar.getInstance();
    Calendar tenMinutesBefore = Calendar.getInstance();
    tenMinutesBefore.add(Calendar.MINUTE, -10); // decrement 10 minutes

    Calendar lastPushWooshRegistrationTime = Calendar.getInstance();
    lastPushWooshRegistrationTime.setTime(new Date(PreferenceUtils.getLastRegistration(context)));

    if (tenMinutesBefore.before(lastPushWooshRegistrationTime)
            && lastPushWooshRegistrationTime.before(nowTime)) {
        // tenMinutesBefore <= lastPushWooshRegistrationTime <= nowTime
        return false;
    }//  w  ww  . j  av  a 2s.c o  m
    return true;
}

From source file:com.vaquerosisd.projectmanager.NewTask.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_task);

    //Set navigation up
    getActionBar().setDisplayHomeAsUpEnabled(true);

    //Initialize database
    db = new ProjectOperations(this);
    db.open();/* ww w  .  jav  a2 s  .co m*/

    //Initialize file operations instance
    fO = new FileOperations(this);

    //Get intent from Projects.class
    Bundle data = getIntent().getExtras();
    projectId = data.getInt("ProjectID");
    projectName = data.getString("ProjectName");

    //Get UI handler references
    final EditText taskNameEditText = (EditText) findViewById(R.id.newTask_TaskName);
    final Spinner statusSpinner = (Spinner) findViewById(R.id.newTask_StatusSpinner);
    final Spinner prioritySpinner = (Spinner) findViewById(R.id.newTask_Priority);
    final EditText percentageDoneEditText = (EditText) findViewById(R.id.newTask_PercentageDone);
    final SeekBar percentageDoneSeekBar = (SeekBar) findViewById(R.id.newTask_PercentageDoneSeekBar);
    final EditText startDateEditText = (EditText) findViewById(R.id.newTask_StartDate);
    final EditText dueDateEditText = (EditText) findViewById(R.id.newTask_DueDate);
    final EditText descriptionEditText = (EditText) findViewById(R.id.newTask_Description);
    final Button addTaskButton = (Button) findViewById(R.id.newTask_AddTask);
    final int[] startDateStrings = { 0, 0, 0 };
    final int[] dueDateStrings = { 0, 0, 0 };

    //Set files they doesn't exist
    String statusItemsString = "New\nIn progress\nPrinting\nOn hold\nCancelled\nReviewing\nDelegated\nCompleted\n";
    fO.createStringFile(statusFileName, statusItemsString);
    String priorityItemsString = "High\nMedium\nLow\n";
    fO.createStringFile(priorityFileName, priorityItemsString);

    //Create and set content for the status and priority spinners
    setSpinner(statusFileName, statusSpinnerAdapter, statusSpinner, true);
    setSpinner(priorityFileName, prioritySpinnerAdapter, prioritySpinner, false);

    percentageDoneEditText.setText("0%");
    //      int statusPosition = statusSpinnerAdapter.getPosition("New");
    //      statusSpinner.setSelection(statusPosition, true);

    addTaskButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            //Get values for the add task
            String projectDir = db.getProjectContentPath(projectId);
            String taskName = taskNameEditText.getText().toString();
            String status = statusSpinner.getSelectedItem().toString();
            String priority = prioritySpinner.getSelectedItem().toString();
            String percentage = percentageDoneEditText.getText().toString();
            int percentageDone = Integer.parseInt(percentage.substring(0, percentage.length() - 1));
            String startDate = startDateEditText.getText().toString();
            String dueDate = dueDateEditText.getText().toString();
            String photoPath = "";
            String description = descriptionEditText.getText().toString();
            String contentPath = projectDir + "/" + taskName;
            Log.i("DEBUG", contentPath);
            File taskContentPath = new File(contentPath);
            taskContentPath.mkdir();

            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_SHORT).show();
                return;
            } else if (!taskName.equals("") && !startDate.equals("") && !dueDate.equals("")) {
                db.addTask(projectId, taskName, status, priority, percentageDone, startDateStrings,
                        dueDateStrings, photoPath, description, contentPath);
                Toast.makeText(getApplicationContext(), R.string.taskAdded, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), R.string.incomplete, Toast.LENGTH_SHORT).show();
                return;
            }

            //Inform of successful adding
            Intent intent = new Intent();
            setResult(RESULT_OK, intent);
            finish();
        }
    });

    //SeekBar listener
    percentageDoneSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            percentageDoneEditText.setText(String.valueOf(progress) + "%");
        }
    });

    //StartDate click listener
    startDateEditText.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            showDatePickerDialog(arg0, STARTDATE_DIALOG_TAG, startDateEditText, startDateStrings);
        }
    });

    //StartDate click listener
    dueDateEditText.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            showDatePickerDialog(arg0, DUEDATE_DIALOG_TAG, dueDateEditText, dueDateStrings);
        }
    });
}

From source file:com.android.deskclock.alarms.AlarmStateManager.java

/**
 * Fix and update all alarm instance when a time change event occurs.
 *
 * @param context application context/*from  w  ww  .j a  va 2  s.  com*/
 */
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);
        if (alarm == null) {
            unregisterInstance(context, instance);
            AlarmInstance.deleteInstance(contentResolver, instance.mId);
            LogUtils.e("Found instance without matching alarm; deleting instance %s", instance);
            continue;
        }
        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.deleteInstanceAndUpdateParent(context, instance);
        } else {
            registerInstance(context, instance, false);
        }
    }

    updateNextAlarm(context);
}

From source file:com.nridge.core.base.field.FieldRange.java

/**
 * Return <i>true</i> if the calendar instance is within the
 * defined range of values or <i>false</i> otherwise.
 *
 * @param aValue Calendar instance./*  w ww.j  ava2 s .  c  om*/
 *
 * @return <i>true</i> or <i>false</i>
 */
public boolean isValid(Calendar aValue) {
    return ((aValue.after(mMinCalendar)) && (aValue.before(mMaxCalendar)));
}

From source file:net.frontlinesms.plugins.reminders.RemindersThinletTabController.java

/**
 * Schedule a Reminder// ww w  .ja  v a 2 s .  co  m
 */
public void scheduleReminder(Reminder reminder) {
    LOG.debug("Callback.scheduleReminder: " + reminder);
    if (reminder != null && reminder.getStatus() != Status.SENT) {
        Calendar start = (Calendar) reminder.getStartCalendar().clone();
        Calendar end = reminder.getEndCalendar();
        Calendar now = Calendar.getInstance();
        if (reminder.getPeriod() > 0) {
            while (start.before(now)) {
                start.add(Calendar.MILLISECOND, (int) reminder.getPeriod());
            }
            LOG.debug("Reminder Scheduled: " + reminder);
            long startDelay = start.getTimeInMillis() - now.getTimeInMillis();
            ScheduledFuture<?> future = this.scheduler.scheduleAtFixedRate(reminder, startDelay,
                    reminder.getPeriod(), TimeUnit.MILLISECONDS);
            this.futures.put(reminder, future);

            LOG.debug("Expiry Scheduled: " + reminder.getEndCalendar().getTime());
            long endDelay = end.getTimeInMillis() - now.getTimeInMillis();
            ExpiredReminder expiredReminder = new ExpiredReminder(reminder);
            ScheduledFuture<?> expiry = this.scheduler.schedule(expiredReminder, endDelay,
                    TimeUnit.MILLISECONDS);
            this.expired.put(reminder, expiry);
        } else {
            LOG.debug("Reminder Scheduled: " + reminder);
            long startDelay = start.getTimeInMillis() - now.getTimeInMillis();
            ScheduledFuture<?> future = this.scheduler.schedule(reminder, startDelay, TimeUnit.MILLISECONDS);
            this.futures.put(reminder, future);
        }
    }
}

From source file:org.artifactory.repo.snapshot.SnapshotVersionsRetriever.java

@Override
protected void internalCollectVersionsItems(StoringRepo repo, ItemNode node) {
    if (node.isFolder()) {
        List<ItemNode> children = node.getChildren();
        for (ItemNode child : children) {
            internalCollectVersionsItems(repo, child);
        }//from w  w w.  j  a  va2  s.c om
    } else {
        RepoPath itemRepoPath = node.getRepoPath();
        ModuleInfo itemModuleInfo = repo.getItemModuleInfo(itemRepoPath.getPath());

        Calendar itemCreated = Calendar.getInstance();
        ItemInfo itemInfo = node.getItemInfo();
        itemCreated.setTimeInMillis(itemInfo.getCreated());

        String uniqueRevision = itemModuleInfo.getFileIntegrationRevision();

        //If we already keep a creation date for this child's unique revision
        if (integrationCreationMap.containsKey(uniqueRevision)) {

            //If the current child's creation date precedes the existing one
            Calendar existingIntegrationCreation = integrationCreationMap.get(uniqueRevision);
            if (itemCreated.before(existingIntegrationCreation)) {

                //Update the reference of all the children with the same unique integration
                integrationCreationMap.put(uniqueRevision, itemCreated);
                Collection<ItemInfo> itemsToRelocate = versionsItems.removeAll(existingIntegrationCreation);
                versionsItems.putAll(itemCreated, itemsToRelocate);
                versionsItems.put(itemCreated, itemInfo);
            } else {

                //Child's creation date isn't newer, just add it
                versionsItems.put(existingIntegrationCreation, itemInfo);
            }
        } else {
            //No reference exists yet, create one
            integrationCreationMap.put(uniqueRevision, itemCreated);
            versionsItems.put(itemCreated, itemInfo);
        }
    }
}

From source file:org.fenixedu.academic.ui.struts.action.publico.RoomSiteViewerDispatchAction.java

public ActionForward roomViewer(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String roomId = request.getParameter("roomId");
    String roomName = request.getParameter("roomName");
    if (roomId == null) {
        roomId = (String) request.getAttribute("roomId");
    }/*  w w w . java 2s. co m*/
    if (roomName == null) {
        roomName = (String) request.getAttribute("roomName");

    }
    request.setAttribute("roomName", roomName);
    request.setAttribute("roomId", roomId);
    RoomKey roomKey = null;
    Space room = null;
    if (roomName != null || roomId != null) {
        if (roomName != null) {
            roomKey = new RoomKey(roomName);
        }
        if (roomId != null) {
            room = FenixFramework.getDomainObject(roomId);
            if (!FenixFramework.isDomainObjectValid(room)) {
                room = null;
            }
        }
        InfoSiteRoomTimeTable bodyComponent = new InfoSiteRoomTimeTable();
        DynaActionForm indexForm = (DynaActionForm) form;
        Integer indexWeek = (Integer) indexForm.get("indexWeek");
        // Integer executionPeriodID = (Integer)
        // indexForm.get("selectedExecutionPeriodID");
        String executionPeriodIDString = request.getParameter("selectedExecutionPeriodID");
        if (executionPeriodIDString == null) {
            executionPeriodIDString = (String) request.getAttribute("selectedExecutionPeriodID");
        }
        String executionPeriodID = (executionPeriodIDString != null) ? executionPeriodIDString : null;
        if (executionPeriodID == null) {
            try {
                // executionPeriodID = (Integer)
                // indexForm.get("selectedExecutionPeriodID");
                executionPeriodID = indexForm.get("selectedExecutionPeriodID").equals("") ? null
                        : (String) indexForm.get("selectedExecutionPeriodID");
            } catch (IllegalArgumentException ex) {
            }
        }
        Calendar today = new DateMidnight().toCalendar(null);
        ArrayList weeks = new ArrayList();

        InfoExecutionPeriod executionPeriod;
        if (executionPeriodID == null) {
            executionPeriod = ReadCurrentExecutionPeriod.run();
            executionPeriodID = executionPeriod.getExternalId();
            try {
                indexForm.set("selectedExecutionPeriodID", executionPeriod.getExternalId().toString());
            } catch (IllegalArgumentException ex) {
            }
        } else {
            executionPeriod = ReadExecutionPeriodByOID.run(executionPeriodID);
        }

        // weeks
        Calendar begin = Calendar.getInstance();
        begin.setTime(executionPeriod.getBeginDate());
        Calendar end = Calendar.getInstance();
        end.setTime(executionPeriod.getEndDate());
        ArrayList weeksLabelValueList = new ArrayList();
        begin.add(Calendar.DATE, Calendar.MONDAY - begin.get(Calendar.DAY_OF_WEEK));
        int i = 0;
        boolean selectedWeek = false;
        while (begin.before(end) || begin.before(Calendar.getInstance())) {
            Calendar day = Calendar.getInstance();
            day.setTimeInMillis(begin.getTimeInMillis());
            weeks.add(day);
            String beginWeekString = DateFormatUtils.format(begin.getTime(), "dd/MM/yyyy");
            begin.add(Calendar.DATE, 5);
            String endWeekString = DateFormatUtils.format(begin.getTime(), "dd/MM/yyyy");
            weeksLabelValueList.add(
                    new LabelValueBean(beginWeekString + " - " + endWeekString, new Integer(i).toString()));
            begin.add(Calendar.DATE, 2);
            if (!selectedWeek && indexWeek == null && Calendar.getInstance().before(begin)) {
                indexForm.set("indexWeek", new Integer(i));
                selectedWeek = true;
            }
            i++;
        }

        final Collection<ExecutionSemester> executionSemesters = rootDomainObject.getExecutionPeriodsSet();
        final List<LabelValueBean> executionPeriodLabelValueBeans = new ArrayList<LabelValueBean>();
        for (final ExecutionSemester ep : executionSemesters) {
            if (ep.getState().equals(PeriodState.OPEN) || ep.getState().equals(PeriodState.CURRENT)) {
                executionPeriodLabelValueBeans.add(new LabelValueBean(
                        ep.getName() + " " + ep.getExecutionYear().getYear(), ep.getExternalId().toString()));
            }
        }
        request.setAttribute(PresentationConstants.LABELLIST_EXECUTIONPERIOD, executionPeriodLabelValueBeans);

        request.setAttribute(PresentationConstants.LABELLIST_WEEKS, weeksLabelValueList);
        if (indexWeek != null) {
            final int xpto = indexWeek.intValue();
            if (xpto < weeks.size()) {
                today = (Calendar) weeks.get(xpto);
            } else {
                today = (Calendar) weeks.iterator().next();
                indexForm.set("indexWeek", new Integer(0));
            }
        }

        try {
            InfoSiteRoomTimeTable component = null;
            if (room != null) {
                component = run(room, today, executionPeriodID);
            } else {
                if (roomKey != null) {
                    component = run(roomKey, today, executionPeriodID);
                }
            }
            request.setAttribute("component", component);
        } catch (NonExistingServiceException e) {
            throw new NonExistingActionException(e);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
        return mapping.findForward("roomViewer");
    }
    throw new FenixActionException();

}

From source file:org.kuali.ext.mm.integration.coa.businessobject.FinancialAccount.java

/**
 * This method determines whether the account is expired or not. Note that if Expiration Date is the same date as testDate, then
 * this will return false. It will only return true if the account expiration date is one day earlier than testDate or earlier.
 * Note that this logic ignores all time components when doing the comparison. It only does the before/after comparison based on
 * date values, not time-values.// w  w w.java2  s . co  m
 * 
 * @param testDate - Calendar instance with the date to test the Account's Expiration Date against. This is most commonly set to
 *        today's date.
 * @return true or false based on the logic outlined above
 */
public boolean isExpired(Calendar testDt) {
    if (this.accountExpirationDate == null) {
        return false;
    }
    Calendar testDate = DateUtils.truncate(testDt, Calendar.DAY_OF_MONTH);
    Calendar acctDate = Calendar.getInstance();
    acctDate.setTime(this.accountExpirationDate);
    acctDate = DateUtils.truncate(acctDate, Calendar.DAY_OF_MONTH);
    // if the Account Expiration Date is before the testDate
    if (acctDate.before(testDate)) {
        return true;
    }
    return false;
}

From source file:com.meetingninja.csse.tasks.TasksFragment.java

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;/*from  w ww  .  j a  v a 2s .  co m*/
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (rowView == null) {
        rowView = inflater.inflate(R.layout.list_item_task, null);
        viewHolder = new ViewHolder();

        viewHolder.title = (TextView) rowView.findViewById(R.id.list_task_title);
        viewHolder.deadline = (TextView) rowView.findViewById(R.id.list_task_deadline);
        viewHolder.background = rowView.findViewById(R.id.list_task_holder);

        rowView.setTag(viewHolder);
    } else
        viewHolder = (ViewHolder) rowView.getTag();

    // Setup from the meeting_item XML file
    Task task = tasks.get(position);

    viewHolder.title.setText(task.getTitle());
    viewHolder.deadline
            .setText("Deadline:  " + MyDateUtils.JODA_APP_DATE_FORMAT.print(task.getEndTimeInMillis()));

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(task.getEndTimeInMillis());
    cal.add(Calendar.DAY_OF_MONTH, -1);
    if (task.getEndTimeInMillis() == 0L) {

    } else if (task.getIsCompleted()) {
        viewHolder.background.setBackgroundColor(Color.rgb(53, 227, 111));
    } else if (cal.before(Calendar.getInstance())) {
        viewHolder.background.setBackgroundColor(Color.rgb(255, 51, 51));
    } else {
        viewHolder.background.setBackground(null);
    }

    return rowView;
}

From source file:com.microsoft.tfs.client.common.ui.commands.search.WorkItemSearchCommand.java

/**
 * Checks that the {@link Date} is within the supported range of dates for
 * work item queries. This method is present because the messages from the
 * client-side WIQL parser and query builder are hard to understand in
 * overflow or underflow cases.//  w w  w  .j a v a2  s  . c o m
 *
 * @param date
 *        the date to check
 * @throws WITypeConverterException
 *         for consistency with core validation methods
 */
private void throwIfDateOutOfRange(final Date date) throws WITypeConverterException {
    final Calendar cal = Calendar.getInstance();
    cal.setTime(date);

    if (cal.before(PropertyValidation.MIN_ALLOWED_DATE_TIME)
            || cal.after(PropertyValidation.MAX_ALLOWED_DATE_TIME)) {
        throw new WITypeConverterException(
                MessageFormat.format(Messages.getString("WorkItemSearchCommand.DateOutOfRangeFormat"), //$NON-NLS-1$
                        rangeErrorDateFormatter.format(date),
                        rangeErrorDateFormatter.format(PropertyValidation.MIN_ALLOWED_DATE_TIME.getTime()),
                        rangeErrorDateFormatter.format(PropertyValidation.MAX_ALLOWED_DATE_TIME.getTime())));
    }
}