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.towerlabs.yildizyemek.JSonProcess.java

public void init() throws JSONException, ParseException, LastDayException {

    jsonArray = new JSONArray(this.rawText);

    datesDate = new ArrayList<Date>();
    datesString = new ArrayList<String>();

    Log.d("available", String.valueOf(jsonArray.length()));

    jsonObject = new JSONObject[jsonArray.length()];

    int tempIndex = 0;

    for (int i = 0; i < jsonArray.length(); i++) {
        jsonObject[i] = jsonArray.getJSONObject(i);

        Iterator<?> it = jsonObject[i].keys();
        Date tempDate = null;
        while (it.hasNext()) {
            // Log.d("iterator", (String) it.next());
            String tempKey = (String) it.next();
            datesString.add(i, tempKey);

            tempDate = new SimpleDateFormat("dd.MM.yyyy", Locale.getDefault()).parse(tempKey);

            datesDate.add(i, tempDate);//w w  w  . j  av  a  2  s .c o m

        }

        if (MainActivity.dateFormat.format(tempDate)
                .equalsIgnoreCase(MainActivity.dateFormat.format(new Date())))
            tempIndex = i;
        else if ((tempDate.compareTo(new Date()) < 0)) {
            tempIndex = i + 1;
        }

    }

    if (tempIndex > (jsonArray.length() - 1)) {
        setIndexPlus(jsonArray.length());
        throw new LastDayException();
    }

    else
        setIndexPlus(tempIndex);

    Log.d("index", String.valueOf(indexPlus));

}

From source file:org.kuali.kpme.tklm.time.missedpunch.web.MissedPunchLookupableImpl.java

private List<MissedPunchBo> filterByActionTime(List<MissedPunchBo> results, String actionTimeString)
        throws ParseException {
    List<MissedPunchBo> resultList = new LinkedList<MissedPunchBo>();

    SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
    Date actionDateTime = null;
    try {/*from w  w w .  ja va2 s.  c o m*/
        actionDateTime = sdf.parse(actionTimeString);
    } catch (ParseException e) {
        GlobalVariables.getMessageMap().putError("lookupCriteria[actionTime]", "error.invalidTime",
                actionTimeString);
        throw e;
    }

    for (MissedPunchBo mp : results) {
        String mpActionTime = mp.getActionTime();
        Date mpActionTimeDate = sdf.parse(mpActionTime);
        boolean added = actionDateTime.compareTo(mpActionTimeDate) == 0 ? resultList.add(mp) : false;
    }
    return resultList;
}

From source file:ch.algotrader.service.CalendarServiceImpl.java

/**
 * {@inheritDoc}/*from w w w . ja  v a2s  .  co  m*/
 */
@Override
public boolean isOpen(final long exchangeId, final Date dateTime) {

    Validate.notNull(dateTime, "Data time is null");

    Date lastRequestTime = this.lastRequestTimeMap.get(exchangeId);
    if (lastRequestTime != null && dateTime.compareTo(lastRequestTime) > 0) {
        Date openTime = this.openTimeMap.get(exchangeId);
        Date closeTime = this.closeTimeMap.get(exchangeId);
        if (closeTime != null) {
            if (closeTime.compareTo(dateTime) > 0) {
                return true;
            } else {
                return isOpenInternal(exchangeId, dateTime);
            }
        } else if (openTime != null) {
            if (openTime.compareTo(dateTime) > 0) {
                return false;
            } else {
                return isOpenInternal(exchangeId, dateTime);
            }
        } else {
            return isOpenInternal(exchangeId, dateTime);
        }
    } else {
        return isOpenInternal(exchangeId, dateTime);
    }
}

From source file:com.itd.dbmrgdao.TestTime_newscanner.java

String FindInOut(String a, String b) throws ParseException {

    //        if (a == null) {
    //            return b;
    //        }/* www.  ja  v a 2  s. c om*/
    SimpleDateFormat parser1 = new SimpleDateFormat("HH:mm");
    Date x = parser1.parse(a);
    Date y = parser1.parse(b);

    try {
        // The Magic happens here i only get the Time out of the Date Object
        SimpleDateFormat parser2 = new SimpleDateFormat("HH:mm");
        x = parser2.parse(parser2.format(x));
        y = parser2.parse(parser2.format(y));

    } catch (ParseException ex) {
        System.err.println(ex);
    }

    return ((x.compareTo(y) <= 0) ? "01" : "04");

}

From source file:com.ebay.erl.mobius.core.model.TupleColumnComparator.java

public int compare(Object object1, Object object2, Configuration conf) throws IOException {
    int _compare_result = Integer.MAX_VALUE;

    ObjectReader reader1 = new ObjectReader(object1, type_for_object1);
    ObjectReader reader2 = new ObjectReader(object2, type_for_object2);

    final Object v1 = reader1.getValue();
    final Object v2 = reader2.getValue();

    setType(Tuple.getType(v1), Tuple.getType(v2));

    if (type_for_object1 == type_for_object2) {
        final byte equal_type = type_for_object1;
        final TupleColumnComparator cmp = new TupleColumnComparator();
        cmp.setType(equal_type, equal_type);
        TupleTypeHandler<Integer> equalTypeComparator = new TupleTypeHandler<Integer>() {

            @Override/*from ww w .j a  v a  2s  . c om*/
            protected Integer on_array() throws IOException {
                Array a1 = (Array) v1;
                Array a2 = (Array) v2;

                return a1.compareTo(a2);
            }

            @Override
            protected Integer on_boolean() throws IOException {
                return compare((Boolean) v1, (Boolean) v2);
            }

            @Override
            protected Integer on_byte() throws IOException {
                return compare((Byte) v1, (Byte) v2);
            }

            @Override
            protected Integer on_byte_array() throws IOException {
                byte[] b1 = (byte[]) v1;
                byte[] b2 = (byte[]) v2;
                int diff = b1.length - b2.length;
                if (diff == 0) {
                    // equal size
                    for (int i = 0; i < b1.length; i++) {
                        diff = compare((Byte) b1[i], (Byte) b2[i]);
                        if (diff != 0)
                            return diff;
                    }
                }
                return diff;
            }

            @Override
            protected Integer on_date() throws IOException {
                return compare((java.sql.Date) v1, (java.sql.Date) v2);
            }

            @Override
            protected Integer on_default() throws IOException {
                throw new IllegalArgumentException("Unsupported type [" + String.format("0x%02X", type) + "]");
            }

            @Override
            protected Integer on_double() throws IOException {
                return compare((Double) v1, (Double) v2);
            }

            @Override
            protected Integer on_float() throws IOException {
                return compare((Float) v1, (Float) v2);
            }

            @Override
            protected Integer on_integer() throws IOException {
                return compare((Integer) v1, (Integer) v2);
            }

            @Override
            protected Integer on_long() throws IOException {
                return compare((Long) v1, (Long) v2);
            }

            @Override
            protected Integer on_null() throws IOException {
                return 0;
            }

            @Override
            protected Integer on_null_writable() throws IOException {
                return 0;
            }

            @Override
            protected Integer on_result_wrapper() throws IOException {

                ResultWrapper w1 = (ResultWrapper) v1;
                ResultWrapper w2 = (ResultWrapper) v2;
                return cmp.compare(w1.getCombinedResult(), w2.getCombinedResult(), null);
            }

            @Override
            protected Integer on_serializable() throws IOException {
                return compare((Comparable) v1, (Comparable) v2);
            }

            @Override
            protected Integer on_short() throws IOException {
                return compare((Short) v1, (Short) v2);
            }

            @Override
            protected Integer on_string() throws IOException {
                return compare((String) v1, (String) v2);
            }

            @Override
            protected Integer on_string_map() throws IOException {
                TreeMap<String, String> m1 = (TreeMap<String, String>) v1;
                TreeMap<String, String> m2 = (TreeMap<String, String>) v2;
                return compare(m1, m2);
            }

            @Override
            protected Integer on_time() throws IOException {
                return compare((java.sql.Time) v1, (java.sql.Time) v2);
            }

            @Override
            protected Integer on_timestamp() throws IOException {
                return compare((java.sql.Timestamp) v1, (java.sql.Timestamp) v2);
            }

            @Override
            protected Integer on_tuple() throws IOException {
                Tuple t1 = (Tuple) v1;
                Tuple t2 = (Tuple) v2;
                return t1.compareTo(t2);
            }

            @Override
            protected Integer on_writable() throws IOException {
                return compare((Comparable) v1, (Comparable) v2);
            }
        };

        _compare_result = equalTypeComparator.handle(equal_type);

    } else {
        // different type
        if (type_for_object1 == Tuple.NULL_TYPE || type_for_object2 == Tuple.NULL_TYPE) {
            // one of them is null type
            _compare_result = (type_for_object1 == Tuple.NULL_TYPE) ? -1 : 1;
        }

        else if (Tuple.isNumericalType(type_for_object1) && type_for_object2 == Tuple.STRING_TYPE) {
            // comparing string with numerical type
            _compare_result = compare(((Number) v1).doubleValue(), Double.parseDouble(((String) v2)));
        } else if (Tuple.isNumericalType(type_for_object2) && type_for_object1 == Tuple.STRING_TYPE) {
            // comparing string with numerical type
            _compare_result = compare(Double.parseDouble(((String) v1)), ((Number) v2).doubleValue());
        }

        else if (Tuple.isNumericalType(type_for_object1) && Tuple.isNumericalType(type_for_object2)) {
            // both are numerical type, but not exact the same

            LOGGER.debug("Comparing two different numberical type:" + Tuple.getTypeString(type_for_object1)
                    + " vs " + Tuple.getTypeString(type_for_object2));

            _compare_result = compare(((Number) v1).doubleValue(), ((Number) v2).doubleValue());

        } else if (Tuple.isDateType(type_for_object1) && Tuple.isDateType(type_for_object2)) {
            // both are date type, but not exact the same
            LOGGER.debug("Comparing two different date type:" + Tuple.getTypeString(type_for_object1) + " vs "
                    + Tuple.getTypeString(type_for_object2));

            if (type_for_object1 == Tuple.TIME_TYPE || type_for_object2 == Tuple.TIME_TYPE) {
                // cannot compare java.sql.Time type with java.sql.Date or java.sql.Timestamp
                throw new IllegalArgumentException(
                        "Cannot compare two columns with different types, column1 type:"
                                + Tuple.getTypeString(Tuple.getType(object1)) + ", colum2 type:"
                                + Tuple.getTypeString(Tuple.getType(object2)));
            }

            // one of them is java.sql.Date, the other one is java.sql.Timestamp,
            java.util.Date d1 = (java.util.Date) v1;
            java.util.Date d2 = (java.util.Date) v2;
            _compare_result = d1.compareTo(d2);
        }

        else {
            throw new IllegalArgumentException("Cannot compare two columns with different types, column1 type:"
                    + Tuple.getTypeString(Tuple.getType(object1)) + ", colum2 type:"
                    + Tuple.getTypeString(Tuple.getType(object2)));
        }
    }

    // comparing complete
    if (_compare_result == Integer.MAX_VALUE)
        throw new IllegalArgumentException();
    else
        return _compare_result;
}

From source file:org.sofun.core.member.MemberServiceImpl.java

@Override
public boolean mustMemberAcceptPolicy(Member member) {
    final String latestStr = (String) Configuration.getProperties().get("betkup.policy.latest");
    final SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
    Date latest = null;//  www.  ja va 2s .  co m
    try {
        latest = sf.parse(latestStr);
    } catch (ParseException e) {
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        log.error("An error occured trying to parse latest policy date." + " Check sofun.properties");
        return false;
    }
    final Date memberLatest = member.getPolicyAcceptanceDate();
    return memberLatest.compareTo(latest) < 0;
}

From source file:org.alfresco.repo.node.MLPropertyInterceptor.java

/**
 * Ensure that content is spoofed for empty translations.
 *///  ww w.j a  v  a  2  s .  c  o m
private Serializable convertOutboundProperty(NodeRef nodeRef, NodeRef pivotNodeRef, QName propertyQName,
        Serializable outboundValue) {
    Serializable ret = null;
    if (outboundValue == null) {
        ret = null;
    }
    if (outboundValue instanceof MLText) {
        // It is MLText
        MLText mlText = (MLText) outboundValue;
        ret = getClosestValue(mlText);
    } else if (isCollectionOfMLText(outboundValue)) {
        Collection<?> col = (Collection<?>) outboundValue;
        ArrayList<String> answer = new ArrayList<String>(col.size());
        Locale closestLocale = getClosestLocale(col);
        for (Object o : col) {
            MLText mlText = (MLText) o;
            String value = mlText.get(closestLocale);
            if (value != null) {
                answer.add(value);
            }
        }
        ret = answer;
    } else if (pivotNodeRef != null) // It is an empty translation
    {
        if (propertyQName.equals(ContentModel.PROP_MODIFIED)) {
            // An empty translation's modified date must be the later of its own
            // modified date and the pivot translation's modified date
            Date emptyLastModified = (Date) outboundValue;
            Date pivotLastModified = (Date) nodeService.getProperty(pivotNodeRef, ContentModel.PROP_MODIFIED);
            if (emptyLastModified.compareTo(pivotLastModified) < 0) {
                ret = pivotLastModified;
            } else {
                ret = emptyLastModified;
            }
        } else if (propertyQName.equals(ContentModel.PROP_CONTENT)) {
            // An empty translation's cm:content must track the cm:content of the
            // pivot translation.
            ret = nodeService.getProperty(pivotNodeRef, ContentModel.PROP_CONTENT);
        } else {
            ret = outboundValue;
        }
    } else {
        ret = outboundValue;
    }
    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Converted outbound property: \n" + "   NodeRef:        " + nodeRef + "\n"
                + "   Property:       " + propertyQName + "\n" + "   Before:         " + outboundValue + "\n"
                + "   After:          " + ret);
    }
    return ret;
}

From source file:org.apache.cloudstack.api.response.QuotaResponseBuilderImpl.java

@Override
public QuotaTariffVO updateQuotaTariffPlan(QuotaTariffUpdateCmd cmd) {
    final int quotaType = cmd.getUsageType();
    final BigDecimal quotaCost = new BigDecimal(cmd.getValue());
    final Date effectiveDate = _quotaService.computeAdjustedTime(cmd.getStartDate());
    final Date now = _quotaService.computeAdjustedTime(new Date());
    // if effective date is in the past return error
    if (effectiveDate.compareTo(now) < 0) {
        throw new InvalidParameterValueException(
                "Incorrect effective date for tariff " + effectiveDate + " is less than now " + now);
    }//w w  w  .ja  v a 2 s . c o m
    QuotaTypes quotaConstant = QuotaTypes.listQuotaTypes().get(quotaType);
    if (quotaConstant == null) {
        throw new InvalidParameterValueException("Quota type does not exists " + quotaType);
    }

    QuotaTariffVO result = null;
    result = new QuotaTariffVO(quotaType);
    result.setUsageName(quotaConstant.getQuotaName());
    result.setUsageUnit(quotaConstant.getQuotaUnit());
    result.setUsageDiscriminator(quotaConstant.getDiscriminator());
    result.setCurrencyValue(quotaCost);
    result.setEffectiveOn(effectiveDate);
    result.setUpdatedOn(now);
    result.setUpdatedBy(cmd.getEntityOwnerId());

    if (s_logger.isDebugEnabled()) {
        s_logger.debug(String.format(
                "Updating Quota Tariff Plan: New value=%s for resource type=%d effective on date=%s", quotaCost,
                quotaType, effectiveDate));
    }
    _quotaTariffDao.addQuotaTariff(result);

    return result;
}

From source file:ca.queensu.cs.sail.mailboxmina2.main.modules.ThreadsModule.java

/**
 * This heuristic creates associations based on the subject and a time
 * window Default Time window is 1 month
 *///ww w  .  j a  v  a2 s .  co  m
private void heuristicSubject(List<MM2Message> messages, Connection connection) {

    // This is the msg_id ==> Date
    Hashtable<String, Date> msg_id_to_date = new Hashtable<String, Date>();

    // This is (original) subject ==> msg_id
    Hashtable<String, String> subject_to_msg_id = new Hashtable<String, String>();

    // This is msg_id ==> (processed) subject
    Hashtable<String, String> msg_id_to_subject = new Hashtable<String, String>();

    // This is child ==> parent
    Hashtable<String, String> msg_id_to_msg_id = new Hashtable<String, String>();

    // Capture the most commong reply patterns
    // Fw: Re: Aw: Wg: 
    Pattern reply_pattern = Pattern.compile(
            "^(\\[.*?\\] )?(([rR][eE]:)|([aA][wW]:)|([fF][wW]:)|([wW][gG]:)|([fF][wW][dD]:)|([wW][tT][rR]:)|([aA]ntwort:))(.*?)$");

    try {
        for (MM2Message msg : messages) {
            String msg_id = msg.getHeaderEntry("msg_id");
            msg_id_to_date.put(msg_id, msg.getMsg_date());
            // We assume the subject to be at least ""
            String raw_subject = msg.getSubject();
            // Determine whether the subject describes a reply or an original posting
            Matcher matcher = reply_pattern.matcher(raw_subject);
            if (matcher.matches()) {
                String stripped_subject = matcher.group(matcher.groupCount());
                Main.getLogger().debug(5, this,
                        "I think message is a reply and the original subject is: " + stripped_subject.trim());
                // Store the information in the forward table
                msg_id_to_subject.put(msg_id, stripped_subject.trim());
            } else {
                // We think that this is not a reply - hence it must be an original posting ;-)
                subject_to_msg_id.put(raw_subject, msg_id);
                Main.getLogger().debug(5, this,
                        "I think message is an original posting: " + raw_subject.trim());
            }
        }

        // Now we need to find parent relations by subject.
        // Still we will apply a sliding window approach using a given offset
        // to make sure, we don't capture events of people re-using old subject names

        for (String child_msg_id : msg_id_to_subject.keySet()) {
            String origSubj = msg_id_to_subject.get(child_msg_id);
            String parent_msg_id = subject_to_msg_id.get(origSubj);
            // If we found an entry in the table
            if (parent_msg_id != null) {
                // Check if the potential parent is (OFFSET) older than child
                Date d1 = msg_id_to_date.get(parent_msg_id);
                Date d2 = DateUtils.addMonths(msg_id_to_date.get(child_msg_id), OFFSET);
                if (d1.compareTo(d2) >= 0) {
                    Main.getLogger().debug(5, this,
                            "I know that message " + child_msg_id + " has the parent " + parent_msg_id);
                    msg_id_to_msg_id.put(child_msg_id, parent_msg_id);
                }
            }
        }

        Main.getLogger().debug(5, "original posting subjects resolved = " + subject_to_msg_id.size());
        Main.getLogger().debug(5, "subjects resolved replys = " + msg_id_to_subject.size());

        // Store the parents and roots into the database
        Main.getLogger().log("The heuristic could resolve " + msg_id_to_msg_id.size() + " parent relations!");
        Main.getLogger().log("Storing associations found by in-reply-to heuristic in the database...");
        storeParents(msg_id_to_msg_id, connection);

    } catch (Exception e) {
        Main.getLogger().error("Error storing messages for heuristic in-reply!", e);
    }
}

From source file:org.sakaiproject.signup.restful.SignupEvent.java

/**
 * This method will check if the current time has already passed the signup
 * deadline//from   w  w  w.j  a  v a 2  s .  c  o m
 * 
 * @return true if the current time has already passed the signup deadline
 */
public boolean isPassedDeadline() {
    Date today = new Date();
    int value = today.compareTo(signupDeadline);
    return value > 0;
}