Example usage for java.util Date compareTo

List of usage examples for java.util Date compareTo

Introduction

In this page you can find the example usage for java.util Date compareTo.

Prototype

public int compareTo(Date anotherDate) 

Source Link

Document

Compares two Dates for ordering.

Usage

From source file:com.ess.tudarmstadt.de.sleepsense.usersdata.UsersDataFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true);//ww  w . j  a v  a2  s  . c o  m

    LocalTransformationDBMS db = new LocalTransformationDBMS(getActivity().getApplicationContext());
    db.open();
    sleepData = db.getAllSleepData();

    // Sort the time of sleepData in decimal format, e.g 13:32 means 13,32
    Collections.sort(sleepData, new Comparator<TrafficData>() {

        @Override
        public int compare(TrafficData arg0, TrafficData arg1) {
            SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy_hh:mm");
            int compareResult = 0;
            try {
                Date arg0Date = format.parse(arg0.getTrafficDate() + "_"
                        + new DecimalFormat("00.00").format(arg0.getxValue()).replaceAll("\\,", ":"));
                Date arg1Date = format.parse(arg1.getTrafficDate() + "_"
                        + new DecimalFormat("00.00").format(arg1.getxValue()).replaceAll("\\,", ":"));
                compareResult = arg0Date.compareTo(arg1Date);
            } catch (ParseException e) {
                e.printStackTrace();
                compareResult = arg0.getTrafficDate().compareTo(arg1.getTrafficDate());
            }
            return compareResult;
        }
    });

    db.close();

    mArrayAdapter = new mArrayAdapter(getActivity(), getActivity().getApplicationContext());
    mArrayAdapter.addAll(sleepData);

    setListAdapter(mArrayAdapter);
    Button addEntry = (Button) rootView.findViewById(R.id.btn_add_item);
    addEntry.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            addEntryRow();
        }
    });

}

From source file:com.aurel.track.linkType.MsProjectLinkTypeBL.java

/**
 * This method checks if moving a parent work item and descendant's violates MS. Proj. link dependency.
 * In case of violation returns a Set with violated Dependencies, otherwise saves moved work items and
 * cascades all descendants. In case of one descendant work item is linked the successor work item
 * will be cascaded./* ww w.j  a v a2  s.c  o m*/
 *
 * @param workItemID
 * @param movedWorkItem
 * @param personID
 * @param oldStartDate
 * @param oldEndDate
 * @param startDate
 * @param endDate
 * @param locale
 * @param msProjectLinkTypeIDs
 * @param itemCascadeMap
 * @return
 */
private static Set<Integer> checkChildrens(Integer workItemID, TWorkItemBean movedWorkItem, Integer personID,
        Date oldStartDate, Date oldEndDate, Date startDate, Date endDate, Locale locale,
        List<Integer> msProjectLinkTypeIDs, Map<Integer, WorkItemWithNewCascadedDates> itemCascadeMap) {
    Set<Integer> violatedDependencies = new HashSet<Integer>();
    List<TWorkItemBean> childrens = ItemBL.getChildren(workItemID);
    if (childrens.isEmpty()) {
        return violatedDependencies;
    }
    int numberOfMovedDays = 0;
    int numberOfWorkedDaysFromMovedDays = 0;
    if (oldStartDate.compareTo(startDate) != 0 && oldEndDate.compareTo(endDate) != 0) {
        numberOfMovedDays = getNumberOfDaysBetweenDates(oldStartDate, startDate, false);
        if (numberOfMovedDays < 0) {
            numberOfWorkedDaysFromMovedDays = getNumberOfWorkDaysFromMovedIntervall(endDate, oldEndDate);
        } else {
            numberOfWorkedDaysFromMovedDays = getNumberOfWorkDaysFromMovedIntervall(oldStartDate, startDate);
        }
    }
    List<WorkItemWithNewCascadedDates> touchedDescendantWorkItems = new ArrayList<WorkItemWithNewCascadedDates>();
    List<TWorkItemBean> allDescendant = new ArrayList<TWorkItemBean>();
    getAllChildrens(childrens, allDescendant, workItemID);
    Map<Integer, Map<TWorkItemBean, Set<TWorkItemBean>>> workItemIDToWorkItemToChildIDMap = createWorkItemIDToWorkItemToChildIDMap(
            allDescendant, movedWorkItem);
    for (Map.Entry<Integer, Map<TWorkItemBean, Set<TWorkItemBean>>> entry : workItemIDToWorkItemToChildIDMap
            .entrySet()) {
        Map<TWorkItemBean, Set<TWorkItemBean>> parentToChild = entry.getValue();
        TWorkItemBean parent = parentToChild.keySet().iterator().next();
        Set<TWorkItemBean> childs = parentToChild.get(parent);
        for (TWorkItemBean childWorkItem : childs) {
            Set<Integer> violatedPredDependencies = checkSuccMoveValidity(getStartDate(childWorkItem),
                    getEndDate(childWorkItem), childWorkItem.getObjectID(), personID, null);
            if (violatedPredDependencies.isEmpty()) {
                if (getStartDate(childWorkItem) != null && getEndDate(childWorkItem) != null) {
                    Date[] newStartEndDate = cascadeWorkItemBySuperior(numberOfMovedDays,
                            numberOfWorkedDaysFromMovedDays, childWorkItem);
                    Set<Integer> problems = checkSuccMoveValidity(newStartEndDate[0], newStartEndDate[1],
                            childWorkItem.getObjectID(), personID, null);
                    if (problems.size() > 0) {
                        for (Integer id : problems) {
                            violatedDependencies.add(id);
                        }
                    }
                    WorkItemWithNewCascadedDates tmp = new WorkItemWithNewCascadedDates();
                    tmp.setWorkItemBean(childWorkItem);
                    tmp.setStarDate(newStartEndDate[0]);
                    tmp.setEndDate(newStartEndDate[1]);
                    touchedDescendantWorkItems.add(tmp);
                }
            }
        }
    }
    if (violatedDependencies.isEmpty()) {
        storeAllTouchedDescendantWorkItem(touchedDescendantWorkItems, personID, locale, msProjectLinkTypeIDs,
                null);
        return violatedDependencies;
    } else {
        return violatedDependencies;
    }
}

From source file:com.ess.tudarmstadt.de.sleepsense.usersdata.UsersDataFragment.java

private void addToDb() {
    String date = String.valueOf(DateFormat.format("dd-MM-yyyy", calendarPicker));

    LocalTransformationDBMS db = new LocalTransformationDBMS(getActivity().getApplicationContext());
    db.open();// www . ja v  a 2 s  . c  o m
    if (idToUpdate > -1) {
        ContentValues values = new ContentValues();
        values.put(LocalTransformationDB.SLEEP_TIME_COLUMN_SLEEP, sleep);
        values.put(LocalTransformationDB.SLEEP_TIME_COLUMN_WAKE, wake);
        values.put(LocalTransformationDB.SLEEP_TIME_COLUMN_PRBLY, 0.0d);

        int rowUpdated = db.updateRow(LocalTransformationDB.TABLE_SLEEP_TIME, values,
                LocalTransformationDB.SLEEP_TIME_COLUMN_ID + " =?",
                new String[] { String.valueOf(idToUpdate) });

        Log.e(TAG, "number of rows edited:" + rowUpdated);

        for (TrafficData trD : sleepData) {
            if (trD.getTrafficId() == idToUpdate) {
                trD.setxValue(sleep);
                trD.setyValue(wake);
            }
        }
    } else {
        db.addSleepData(date, sleep, wake, 0.0d);
        sleepData.add(new TrafficData(date, -1, sleep, wake));
    }
    db.close();

    Collections.sort(sleepData, new Comparator<TrafficData>() {

        @Override
        public int compare(TrafficData arg0, TrafficData arg1) {
            SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy_hh:mm");
            int compareResult = 0;
            try {
                Date arg0Date = format.parse(arg0.getTrafficDate() + "_"
                        + new DecimalFormat("00.00").format(arg0.getxValue()).replaceAll("\\,", ":"));
                Date arg1Date = format.parse(arg1.getTrafficDate() + "_"
                        + new DecimalFormat("00.00").format(arg1.getxValue()).replaceAll("\\,", ":"));
                compareResult = arg0Date.compareTo(arg1Date);
            } catch (ParseException e) {
                e.printStackTrace();
                compareResult = arg0.getTrafficDate().compareTo(arg1.getTrafficDate());
            }
            return compareResult;
        }
    });

    mArrayAdapter.clear();
    mArrayAdapter.addAll(sleepData);
    ((com.ess.tudarmstadt.de.sleepsense.usersdata.UsersDataFragment.mArrayAdapter) mArrayAdapter).calcPrbly();

    mArrayAdapter.notifyDataSetChanged();

    // clear picker
    calendarPicker = Calendar.getInstance();
    sleep = 0.0d;
    wake = 0.0d;
    idToUpdate = -1;

}

From source file:com.odoo.addons.crm.models.CRMLead.java

/**
 * Setting reminder for lead/opportunity
 *
 * @param row_id/*from  www .j ava 2s  .co  m*/
 */
public void setReminder(int row_id) {
    ODataRow row = browse(row_id);
    String time = " " + BaseSettings.getDayStartTime(mContext);
    Date now = new Date();
    Bundle extra = row.getPrimaryBundleData();
    extra.putString(ReminderUtils.KEY_REMINDER_TYPE, "opportunity");
    if (!row.getString("date_deadline").equals("false")) {
        row.put("date_deadline", row.getString("date_deadline") + time);
        Date date_deadline = ODateUtils.createDateObject(row.getString("date_deadline"),
                ODateUtils.DEFAULT_FORMAT, false);
        if (now.compareTo(date_deadline) < 0) {
            extra.putBoolean("expiry_date", true);
            if (ReminderUtils.get(mContext).resetReminder(date_deadline, extra)) {
                // Nothing to do. Reminder set for expiry date
            }
        }
    }

    if (!row.getString("date_action").equals("false")) {
        row.put("date_action", row.getString("date_action") + time);
        Date date_action = ODateUtils.createDateObject(row.getString("date_action"), ODateUtils.DEFAULT_FORMAT,
                false);
        if (now.compareTo(date_action) < 0) {
            extra.putBoolean("expiry_date", false);
            if (ReminderUtils.get(mContext).resetReminder(date_action, extra)) {
                // Nothing to do. Reminder set for next date action
            }
        }

    }
}

From source file:gov.utah.dts.det.ccl.model.view.AlertFollowUpsNeededView.java

public AlertType getAlertType() throws JSONException, ParseException {
    if (alertType == null) {
        alertType = AlertType.ALERT;/*from  ww  w . java  2 s .co  m*/
        Date now = new Date();
        Date latestCorrectionDate = null;
        for (FindingFollowUpView find : getFindings()) {
            if (latestCorrectionDate == null || latestCorrectionDate.before(find.getCorrectionDate())) {
                latestCorrectionDate = find.getCorrectionDate();
            }
        }
        Date expDt = getFacility().getLicenseExpirationDate();
        //         if (corrDl == null) {
        //            corrDl = DateUtils.addDays(inspectionDate, 30);
        //         }
        if (expDt == null) {
            expDt = DateUtils.addDays(latestCorrectionDate, 60);
        }
        Date window = DateUtils.addDays(expDt, -30);

        //all inspections are required at least 7 days before the expiration date
        if (latestCorrectionDate.compareTo(window) >= 0 && now.compareTo(DateUtils.addDays(expDt, -14)) >= 0) {
            //if we had 30 days or less until the license expiration and we are within 14 days of the license expiration
            alertType = AlertType.RED_ALERT;
        } else if (latestCorrectionDate.compareTo(window) >= 0
                && now.compareTo(DateUtils.addDays(expDt, -21)) >= 0) {
            //if we had 30 days or less until the license expiration and we are within 21 days of the license expiration
            alertType = AlertType.ORANGE_ALERT;
        } else if (now.compareTo(DateUtils.addDays(latestCorrectionDate, 21)) >= 0) {
            //if we had more than 30 days until the license expiration and we are over 21 days past the correction deadline
            alertType = AlertType.RED_ALERT;
        } else if (now.compareTo(DateUtils.addDays(latestCorrectionDate, 14)) >= 0) {
            //if we had more than 30 days until the license expiration and we are over 14 days past the correction deadline
            alertType = AlertType.ORANGE_ALERT;
        }
    }
    return alertType;
}

From source file:org.libreplan.web.orders.OrderElementTreeController.java

public Constraint checkConstraintStartDate() {
    return (comp, value) -> {
        Date startDate = (Date) value;

        if ((startDate != null) && (filterFinishDateOrderElement.getValue() != null)
                && (startDate.compareTo(filterFinishDateOrderElement.getValue()) > 0)) {

            filterStartDateOrderElement.setValue(null);
            throw new WrongValueException(comp, _("must be lower than end date"));
        }/*from  www .  ja v  a 2 s.  c  o m*/
    };
}

From source file:org.libreplan.web.orders.OrderElementTreeController.java

/**
 * Operations to filter the orders by multiple filters.
 *///from  w  ww .  j  a  va  2 s  .com
public Constraint checkConstraintFinishDate() {
    return (comp, value) -> {
        Date finishDate = (Date) value;

        if ((finishDate != null) && (filterStartDateOrderElement.getValue() != null)
                && (finishDate.compareTo(filterStartDateOrderElement.getValue()) < 0)) {

            filterFinishDateOrderElement.setValue(null);
            throw new WrongValueException(comp, _("must be after start date"));
        }
    };
}

From source file:org.dashbuilder.dataset.IntervalBuilderDynamicDate.java

public IntervalList build(DataSetHandler handler, ColumnGroup columnGroup) {
    IntervalDateRangeList results = new IntervalDateRangeList(columnGroup);
    DataSet dataSet = handler.getDataSet();
    List values = dataSet.getColumnById(columnGroup.getSourceId()).getValues();
    if (values.isEmpty()) {
        return results;
    }//w ww  .  java2  s.c  o  m

    // Sort the column dates.
    DataSetSort sortOp = new DataSetSort();
    sortOp.addSortColumn(new ColumnSort(columnGroup.getSourceId(), SortOrder.ASCENDING));
    DataSetHandler sortResults = handler.sort(sortOp);
    List<Integer> sortedRows = sortResults.getRows();
    if (sortedRows == null || sortedRows.isEmpty()) {
        return results;
    }

    // Get the lower & upper limits (discard nulls).
    SortedList sortedValues = new SortedList(values, sortedRows);
    Date minDate = null;
    Date maxDate = null;
    for (int i = 0; minDate == null && i < sortedValues.size(); i++) {
        minDate = (Date) sortedValues.get(i);
    }
    for (int i = sortedValues.size() - 1; maxDate == null && i >= 0; i--) {
        maxDate = (Date) sortedValues.get(i);
    }

    // If min/max are equals then return a single interval.
    DateIntervalType intervalType = calculateIntervalSize(minDate, maxDate, columnGroup);
    if (minDate == null || minDate.compareTo(maxDate) == 0) {

        IntervalDateRange interval = new IntervalDateRange(0, intervalType, minDate, maxDate);
        for (int row = 0; row < sortedValues.size(); row++)
            interval.getRows().add(row);

        results.add(interval);
        results.setIntervalType(columnGroup.getIntervalSize());
        results.setMinValue(minDate);
        results.setMaxValue(maxDate);
        return results;
    }

    // Create the intervals according to the min/max dates.
    Calendar c = firstIntervalDate(intervalType, minDate, columnGroup);
    int index = 0;
    int counter = 0;
    while (c.getTime().compareTo(maxDate) <= 0) {
        Date intervalMinDate = c.getTime();

        // Create the next interval
        nextIntervalDate(c, intervalType, 1);
        Date intervalMaxDate = c.getTime();
        IntervalDateRange interval = new IntervalDateRange(counter++, intervalType, intervalMinDate,
                intervalMaxDate);
        results.add(interval);

        // Add the target rows
        boolean stop = false;
        while (!stop) {
            if (index >= sortedValues.size()) {
                stop = true;
            } else {
                Date dateValue = (Date) sortedValues.get(index);
                Integer row = sortedRows.get(index);
                if (dateValue == null) {
                    index++;
                } else if (dateValue.before(intervalMaxDate)) {
                    interval.getRows().add(row);
                    index++;
                } else {
                    stop = true;
                }
            }
        }
    }

    // Reverse intervals if requested
    boolean asc = columnGroup.isAscendingOrder();
    if (!asc)
        Collections.reverse(results);

    // Return the results
    results.setIntervalType(intervalType.toString());
    results.setMinValue(minDate);
    results.setMaxValue(maxDate);
    return results;
}

From source file:com.sfs.whichdoctor.dao.OnlineToolDAOImpl.java

/**
 * Determine the rotation guid. If the rotation overridden flag
 * is set the existing GUID (if any) is returned.
 *
 * @param ot the online tool/*from w w w .j av a2s  .  co m*/
 * @return the int
 */
private int determineRotationGUID(final OnlineToolBean ot) {

    int rotationGUID = 0;

    if (ot != null) {
        if (ot.getRotationOverridden()) {
            rotationGUID = ot.getRotationGUID();
        } else {
            // Identify the relevant rotations
            Map<String, RotationBean> rts = new TreeMap<String, RotationBean>();

            if (ot.getReferenceGUID() > 0) {
                try {
                    BuilderBean loadDetails = new BuilderBean();
                    loadDetails.setParameter("TRAINING_ROTATIONS", true);

                    PersonBean person = this.personDAO.loadGUID(ot.getReferenceGUID(), loadDetails);

                    if (person != null && person.getRotations() != null) {

                        dataLogger.info("Person " + person.getGUID() + " associated with rotation");

                        for (RotationBean r : person.getRotations()) {
                            Date[] dates = { ot.getStartDate(), ot.getEndDate(), ot.getSubmitted(),
                                    ot.getCompleted() };

                            for (Date date : dates) {
                                if (date != null) {
                                    dataLogger.info("Tool date: " + date);

                                    if (date.compareTo(r.getStartDate()) >= 0
                                            && date.compareTo(r.getEndDate()) <= 0) {
                                        rts.put(buildKey(r.getStartDate(), r.getGUID()), r);

                                        dataLogger.info("Date after rotation " + r.getGUID()
                                                + " start date and before its end");
                                    }
                                }
                            }
                        }
                    }
                } catch (WhichDoctorDaoException wde) {
                    dataLogger.error("Error checking for relevant rotations: " + wde.getMessage());
                }
            }

            // If rts.size() == 0 then there is no obvious relationship.

            if (rts.size() == 1) {
                // A single rotation was identified - set the relationship
                rotationGUID = rts.values().iterator().next().getGUID();
            }

            if (rts.size() > 1) {
                // More than one rotation was found - determine most appropriate
                double percentage = 0;

                for (String key : rts.keySet()) {
                    RotationBean r = rts.get(key);

                    if (rotationGUID == 0) {
                        rotationGUID = r.getGUID();
                    }

                    if (ot.getStartDate() != null) {
                        // Determine what percentage of the online tool was
                        // undertaken during the rotation.
                        double rPercentage = 0;
                        long otTime = 0;
                        Date pStartDate = new Date(ot.getStartDate().getTime());
                        Date pEndDate = new Date(r.getEndDate().getTime());

                        Date[] dates = { ot.getSubmitted(), ot.getEndDate(), ot.getCompleted() };

                        if (r.getStartDate().compareTo(ot.getStartDate()) > 0) {
                            pStartDate = new Date(r.getStartDate().getTime());
                        }

                        for (Date date : dates) {
                            if (date != null) {
                                otTime = date.getTime() - ot.getStartDate().getTime();

                                if (r.getEndDate().compareTo(date) > 0) {
                                    pEndDate = new Date(date.getTime());
                                }
                            }
                        }

                        if (otTime > 0) {
                            rPercentage = (pEndDate.getTime() - pStartDate.getTime()) / otTime;

                            dataLogger.info("Calculated percentage: " + rPercentage);
                        }

                        if (rPercentage > percentage) {
                            dataLogger.info("Current percentage higher than " + percentage);

                            percentage = rPercentage;
                            rotationGUID = r.getGUID();
                        }
                    }
                }
            }
        }
    }

    dataLogger.info("Rotation GUID " + rotationGUID + " identified");
    return rotationGUID;
}

From source file:Implement.Service.TripperServiceImpl.java

@Override
public List<Double> getPriceOfSelectedDate(String selectedDate, PackageDTO packageDTO) throws ParseException {
    String promotionJson = packageDTO.getPromotionJson();
    JsonArray promotions = gson.fromJson(promotionJson, JsonArray.class);
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
    Date selectDate;
    selectDate = format.parse(selectedDate);
    double priceAdult = 0;
    double priceChild = 0;
    for (JsonElement promotion : promotions) {
        JsonObject jsonObject = promotion.getAsJsonObject();
        JsonArray datesArray = jsonObject.get("dates").getAsJsonArray();
        for (JsonElement dateJson : datesArray) {
            String dateStr = dateJson.getAsString();
            Date promotionDate = format.parse(dateStr);
            if (selectDate.compareTo(promotionDate) == 0) {
                priceAdult = jsonObject.get("priceAdult").getAsDouble();
                priceChild = jsonObject.get("priceChild").getAsDouble();
                break;
            }//from   w ww  .  j a va2 s  . c  o m
        }
        if (priceAdult > 0) {
            break;
        }
    }
    List<Double> prices = new ArrayList<Double>();
    if (priceAdult > 0) {
        prices.add(priceAdult);
        prices.add(priceChild);
    } else {
        prices.add(packageDTO.getOrdinaryPriceForAdult());
        prices.add(packageDTO.getOrdinaryPriceForChild());
    }
    return prices;
}