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.yukthi.validators.GreaterThanEqualsValidator.java

@Override
public boolean isValid(Object bean, Object fieldValue) {
    if (bean == null) {
        return true;
    }//from  w w w  .j  a v  a 2 s  .c  om

    //fetch other field value
    Object otherValue = null;

    try {
        otherValue = PropertyUtils.getProperty(bean, greaterThanField);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
        throw new IllegalStateException("Invalid/inaccessible property \"" + greaterThanField
                + "\" specified with matchWith validator in bean: " + bean.getClass().getName());
    }

    //ensure other field value is present and is of same type
    if (fieldValue == null || otherValue == null || !fieldValue.getClass().equals(otherValue.getClass())) {
        return true;
    }

    //number comparison
    if (otherValue instanceof Number) {
        return (((Number) fieldValue).doubleValue() >= ((Number) otherValue).doubleValue());
    }

    //date comparison
    if (otherValue instanceof Date) {
        Date dateValue = DateUtils.truncate((Date) fieldValue, Calendar.DATE);
        Date otherDateValue = DateUtils.truncate((Date) otherValue, Calendar.DATE);

        return (dateValue.compareTo(otherDateValue) >= 0);
    }

    return true;
}

From source file:org.archive.wayback.partition.ToolBarData.java

private void findRelativeLinks() {
    Date cur = curResult.getCaptureDate();

    Date minYear = addYear(cur, -1);
    Date minMonth = addMonth(cur, -1);
    Date addYear = addYear(cur, 1);
    Date addMonth = addMonth(cur, 1);
    Iterator<CaptureSearchResult> itr = results.iterator();
    while (itr.hasNext()) {
        CaptureSearchResult result = itr.next();
        Date d = result.getCaptureDate();
        if (d.compareTo(cur) < 0) {
            prevResult = result;// ww  w  . j a  v  a2  s  .  com
            if (d.compareTo(minMonth) < 0) {
                monthPrevResult = result;
            }
            if (d.compareTo(minYear) < 0) {
                yearPrevResult = result;
            }
        } else if (d.compareTo(cur) > 0) {
            if (nextResult == null) {
                nextResult = result;
            }
            if (d.compareTo(addYear) > 0) {
                if (yearNextResult == null) {
                    yearNextResult = result;
                }
            }
            if (d.compareTo(addMonth) > 0) {
                if (monthNextResult == null) {
                    monthNextResult = result;
                }
            }
        }
    }
}

From source file:com.android.applications.todoist.containers.Tasks.java

public ArrayList<Task> getTasksByDate(Date date, boolean remove) {
    ArrayList<Task> list = new ArrayList<Task>();
    Date dueDate;
    for (int i = 0; i < this.tasks.size(); i++) {
        dueDate = this.tasks.get(i).getDueDate();
        if (dueDate.compareTo(date) == 0) {
            list.add(this.tasks.get(i));
            if (remove) {
                this.tasks.remove(i);
                i--;//  w  ww  .j  av  a 2 s  .  c o  m
            }
        }
    }

    return list;
}

From source file:com.cubusmail.server.mail.util.MessageComparator.java

public int compare(Message msg1, Message msg2) {

    int result = 0;

    if (msg1.isExpunged() || msg2.isExpunged()) {
        return result;
    }//from w  w  w  . j  av  a  2s . c  om

    try {
        if (MessageListFields.SUBJECT == this.field) {
            if (msg1.getSubject() != null && msg2.getSubject() != null) {
                result = msg1.getSubject().compareToIgnoreCase(msg2.getSubject());
            } else {
                result = -1;
            }
        } else if (MessageListFields.FROM == this.field) {
            String fromString1 = MessageUtils.getMailAdressString(msg1.getFrom(), AddressStringType.PERSONAL);
            String fromString2 = MessageUtils.getMailAdressString(msg2.getFrom(), AddressStringType.PERSONAL);
            if (fromString1 != null && fromString2 != null) {
                result = fromString1.compareToIgnoreCase(fromString2);
            } else {
                result = -1;
            }
        } else if (MessageListFields.SEND_DATE == this.field) {
            Date date1 = msg1.getSentDate();
            Date date2 = msg2.getSentDate();
            if (date1 != null && date2 != null) {
                result = date1.compareTo(date2);
            } else {
                result = -1;
            }
        } else if (MessageListFields.SIZE == this.field) {
            int size1 = msg1.getSize();
            int size2 = msg2.getSize();
            result = Integer.valueOf(size1).compareTo(Integer.valueOf(size2));

        }
    } catch (MessagingException e) {
        log.warn(e.getMessage(), e);
    }

    if (!this.ascending) {
        result = result * (-1);
    }

    return result;
}

From source file:com.clican.pluto.dataprocess.dpl.function.impl.MatchPriceAndWeight.java

@SuppressWarnings("unchecked")
public Object calculate(List<Map<String, Object>> rowSet)
        throws CalculationException, PrefixAndSuffixException {
    Map<String, Object> mapRow = new HashMap<String, Object>();
    boolean clear = true;
    Date date = null;//www  .  j  av  a2 s  .co m
    for (Map<String, Object> row : rowSet) {
        date = datePas.getValue(row);
        String weightCode = weightCodePas.getValue(row);
        Number weight = weightPas.getValue(row);
        if (StringUtils.isNotEmpty(weightCode) && clear) {
            previousWeightMap.clear();
            previousResetDuration = resetDurationPas.getValue(row);
            previousDate = datePas.getValue(row);
            clear = false;
        }
        if (StringUtils.isNotEmpty(weightCode)) {
            previousWeightMap.put(weightCode, weight.doubleValue());
        }
    }
    // ???
    boolean changeWeight = !clear;
    if (changeWeight) {
        for (String code : allCodes) {
            if (!previousWeightMap.containsKey(code)) {
                previousWeightMap.put(code, 0d);
            }
        }
        weightMap = new HashMap<String, Double>(previousWeightMap);
    } else {
        if (StringUtils.isNotEmpty(previousResetDuration)) {
            if (previousResetDuration.equals("1D")) {
                weightMap = new HashMap<String, Double>(previousWeightMap);
            } else if (previousResetDuration.equals("1W")) {
                if (!ToChar.toYearAndWeek(previousDate).equals(ToChar.toYearAndWeek(date))) {
                    previousDate = date;
                    weightMap = new HashMap<String, Double>(previousWeightMap);
                }
            } else if (previousResetDuration.equals("1M")) {
                Date temp = DateUtils.addMonths(previousDate, 1);
                if (temp.compareTo(date) <= 0) {
                    previousDate = date;
                    weightMap = new HashMap<String, Double>(previousWeightMap);
                }
            } else if (previousResetDuration.equals("3M")) {
                Date temp = DateUtils.addMonths(previousDate, 3);
                if (temp.compareTo(date) <= 0) {
                    previousDate = date;
                    weightMap = new HashMap<String, Double>(previousWeightMap);
                }
            }
        }
    }

    Set<String> populatePriceSet = new HashSet<String>();
    for (Map<String, Object> row : rowSet) {
        mapRow.put("date", date);
        // ???
        if (weightMap.size() == 0) {
            break;
        }
        String priceCode = priceCodePas.getValue(row);
        if (weightMap.containsKey(priceCode)) {
            populatePriceSet.add(priceCode);
        }
    }
    mapRow.put("date", date);
    if (populatePriceSet.size() == weightMap.size()) {
        for (Map<String, Object> row : rowSet) {
            String priceCode = priceCodePas.getValue(row);
            Number price = pricePas.getValue(row);
            if (StringUtils.isNotEmpty(priceCode) && weightMap.containsKey(priceCode)) {
                if (!mapRow.containsKey("priceMap")) {
                    mapRow.put("priceMap", new HashMap<String, Double>());
                }
                ((Map) mapRow.get("priceMap")).put(priceCode, price.doubleValue());
                if (!mapRow.containsKey("weightMap")) {
                    mapRow.put("weightMap", new HashMap<String, Double>());
                }
                if (!((Map) mapRow.get("weightMap")).containsKey(priceCode)) {
                    ((Map) mapRow.get("weightMap")).put(priceCode, weightMap.get(priceCode));
                }
                if (previousResetDuration.equals("1W") || previousResetDuration.equals("1M")
                        || previousResetDuration.equals("3M")) {
                    // ?????
                    weightMap.put(priceCode, null);
                }
            }
        }
    }

    return mapRow;
}

From source file:org.atomserver.core.dbstore.utils.SeederDBSTest.java

public void testSeedDB() throws Exception {

    if (hasRun) {
        return;/* ww w  .java 2s . co  m*/
    }

    String[] configs = { "/org/atomserver/spring/propertyConfigurerBeans.xml",
            "/org/atomserver/spring/logBeans.xml", "/org/atomserver/spring/storageBeans.xml",
            "/org/atomserver/spring/databaseBeans.xml" };
    ClassPathXmlApplicationContext springFactory = new ClassPathXmlApplicationContext(configs, false);
    springFactory.setClassLoader(new ConfigurationAwareClassLoader(springFactory.getClassLoader()));
    springFactory.refresh();

    try {
        DBSeeder.getInstance(springFactory).seedEntriesClearingFirst();
    } catch (Exception ee) {
        ee.printStackTrace();
    }
    hasRun = true;

    // We should now get an ordered List back
    // SORTED -- From the beginning of time

    EntriesDAO widgetsDAOiBatis = (EntriesDAO) springFactory.getBean("org.atomserver-entriesDAO");

    List sortedList = widgetsDAOiBatis
            .selectEntriesByLastModifiedSeqNum(new BaseFeedDescriptor("widgets", null), ZERO_DATE);
    log.debug("List= " + sortedList);

    Date lastVal = ZERO_DATE;
    long seqNum = 0;
    for (Object obj : sortedList) {
        EntryMetaData widget = (EntryMetaData) obj;

        assertTrue(lastVal.compareTo(widget.getUpdatedDate()) <= 0);
        lastVal = widget.getUpdatedDate();

        assertTrue("expected " + seqNum + " < " + widget.getUpdateTimestamp() + " for " + widget,
                seqNum < widget.getUpdateTimestamp());

        seqNum = widget.getUpdateTimestamp();
    }
}

From source file:com.vmware.identity.util.TimePeriod.java

/**
 *
 * @param pointOfTime//from www. jav  a 2  s.c  om
 *           cannot be null
 * @return if given pointOfTime is in this time period. If this period has
 *         start and end times this point of time can match with start time
 *         but not with end time, meaning if start and end times are not null
 *         the point of time is compared to this interval inclusive the start
 *         time, exclusive the end time.
 */
public boolean contains(Date pointOfTime) {
    Validate.notNull(pointOfTime);

    boolean result = true;

    if (startTime != null) {
        result &= (pointOfTime.compareTo(startTime) >= 0);
    }
    if (endTime != null) {
        result &= pointOfTime.before(endTime);
    }

    return result;
}

From source file:monitoring.tools.AppTweak.java

protected void apiCall() throws MalformedURLException, IOException, JSONException, ParseException {

    String timeStamp = new Timestamp((new Date()).getTime()).toString();

    JSONObject data = urlConnection();/*  w  w  w.  ja va 2 s  .c om*/

    List<MonitoringData> dataList = new ArrayList<>();
    JSONArray reviews = data.getJSONArray("content");
    for (int i = 0; i < reviews.length(); ++i) {

        JSONObject obj = reviews.getJSONObject(i);

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss z");
        Date date = format.parse(obj.getString("date"));

        if (date.compareTo(stamp) > 0) {

            Iterator<?> keys = obj.keys();
            MonitoringData review = new MonitoringData();

            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("id"))
                    review.setReviewID(obj.getString("id"));
                else if (key.equals("author"))
                    review.setAuthorName(obj.getJSONObject("author").getString("name"));
                else if (key.equals("title"))
                    review.setReviewTitle(obj.getString("title"));
                else if (key.equals("body"))
                    review.setReviewText(obj.getString("body"));
                else if (key.equals("date"))
                    review.setTimeStamp(obj.getString("date"));
                else if (key.equals("rating"))
                    review.setStarRating(String.valueOf(obj.getInt("rating")));
                else if (key.equals("version"))
                    review.setAppVersion(obj.getString("version"));
            }

            dataList.add(review);
        }
    }
    //kafka.generateResponseKafka(dataList, timeStamp, id, confId, params.getKafkaTopic());
    kafka.generateResponseIF(dataList, timeStamp, id, confId, params.getKafkaTopic());
    logger.debug("Data sent to kafka endpoint");
    ++id;
}

From source file:org.openvpms.web.workspace.customer.estimate.EstimateEditor.java

/**
 * Invoked when the start time changes. Sets the value to today if start time < today.
 *//*from  w  w  w  .j  ava2  s . co m*/
@Override
protected void onStartTimeChanged() {
    Date start = getStartTime();
    if (start != null) {
        Date now = new Date();
        if (DateRules.compareDates(start, now) < 0) {
            // ensure start date isn't before the current date
            setStartTime(now, true);
        } else {
            Date end = getEndTime();
            if (end != null && end.compareTo(start) < 0) {
                setEndTime(start, true);
            }
        }
    }
}

From source file:edu.uwp.alga.Data.DataLogFragment.java

public void sortLatest(List<String> timeData) {
    Collections.sort(timeData, new Comparator<String>() {
        @Override/*  ww w.  ja v  a2s .  c o m*/
        public int compare(String lhs, String rhs) {
            String lhsTime = lhs.substring(0, 23);
            String rhsTime = rhs.substring(0, 23);

            Date lhsDate = DataUtils.convertToDate(lhsTime);
            Date rhsDate = DataUtils.convertToDate(rhsTime);
            if (lhsDate.compareTo(rhsDate) == -1) {
                return 1;
            } else if (lhsDate.compareTo(rhsDate) == 1) {
                return -1;
            } else
                return 0;
        }

    });

}