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:org.nuxeo.ecm.webapp.widgets.DateRangeValidator.java

public void validateDateRange(FacesContext context, UIComponent component, Object value) {
    Map<String, Object> attributes = component.getAttributes();
    String startDateComponentId = (String) attributes.get("startDateComponentId");
    String endDateComponentId = (String) attributes.get("endDateComponentId");
    if (startDateComponentId == null || endDateComponentId == null) {
        return;/*from  ww  w  .j a  va  2s .c o m*/
    }

    UIInput startDateComp = (UIInput) component.findComponent(startDateComponentId);
    UIInput endDateComp = (UIInput) component.findComponent(endDateComponentId);
    if (startDateComp == null) {
        log.error("Can not find component with id " + startDateComponentId);
        return;
    }

    if (endDateComp == null) {
        log.error("Can not find component with id " + endDateComponentId);
        return;
    }
    Date stratDate = (Date) startDateComp.getLocalValue();
    Date endDate = (Date) endDateComp.getLocalValue();

    if (stratDate != null && endDate != null && endDate.compareTo(stratDate) < 0) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                String.format(messages.get("error.dateRangeValidator.invalidDateRange"), stratDate, endDate),
                null);
        throw new ValidatorException(message);
    }
}

From source file:service.WorkReportService.java

private void sortDataList(List<WorkReportData> dataList) {
    Collections.sort(dataList, new Comparator<WorkReportData>() {

        @Override/*from  w w w.  j a  v a2  s  .c  om*/
        public int compare(WorkReportData o1, WorkReportData o2) {
            Date createDate1 = getDate(o1);
            Date createDate2 = getDate(o2);
            return -(createDate1.compareTo(createDate2));
        }

        private Date getDate(WorkReportData data) {
            if (data.getNotice() != null) {
                return data.getNotice().getNoticeDate();
            } else {
                return data.getLog().getCreateDate();
            }
        }

    });
}

From source file:de.kp.ames.web.core.json.DateCollector.java

public DateCollector() {

    collector = new TreeMap<Date, ArrayList<JSONObject>>(new Comparator<Date>() {
        public int compare(Date date1, Date date2) {
            // this is a descending sorting of two dates
            return (-1) * date1.compareTo(date2);
        }/*from ww  w  .  j  av  a2  s.  co m*/
    });

}

From source file:org.onosproject.drivers.polatis.netconf.PolatisFlowRuleProgrammable.java

private String parseKeyPairCompat() {
    String rev = opticalRevision(handler());
    if (rev == null) {
        throw new IllegalStateException(new NetconfException("Failed to obtain the revision."));
    }//from  w  w w  .j  av  a 2 s. co m
    String keyPairCompat;
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(PAIR_COMPAT_REVISION);

        if (date.compareTo(sdf.parse(rev)) > 0) {
            keyPairCompat = KEY_PAIRS;
        } else {
            keyPairCompat = KEY_PAIR;
        }
    } catch (ParseException e) {
        throw new IllegalArgumentException(
                new NetconfException(String.format("Incorrect date format: %s", rev)));
    }
    return keyPairCompat;
}

From source file:org.cloudfoundry.identity.uaa.scim.job.CloudControllerLastModifiedFilterProcessor.java

private boolean isTargetModifiedMoreRecently(Map<String, ?> source, Map<String, ?> target) {
    Date targetModified = (Date) target.get("lastModified");
    Date sourceModified = (Date) source.get("updated_at");
    return targetModified.compareTo(sourceModified) >= 0;
}

From source file:org.sakaiproject.profile2.model.MessageThread.java

/**
 * Natural sort by order//  ww  w. ja  va2  s .c om
 */
public int compareTo(Object o) {
    Date thisDate = getMostRecentMessage().getDatePosted();
    Date otherDate = ((MessageThread) o).getMostRecentMessage().getDatePosted();
    int lastCmp = thisDate.compareTo(otherDate);
    return (lastCmp != 0 ? lastCmp : thisDate.compareTo(otherDate));
}

From source file:assignment.HTTPResponse.java

public void serve(HTTPRequest httpRequest, OutputStream outputStream, Socket socket)
        throws IOException, ParseException, InterruptedException {
    PrintWriter pw = new PrintWriter(outputStream, true);
    JSONObject obj = new JSONObject();
    if (httpRequest.getHttpMethod().equals("GET")) {

        String[] url = (httpRequest.getResourceURI()).split("\\?");
        if (url[0].equals("/request")) {
            String ar1[] = url[1].split("&");
            String[] name1 = ar1[0].split("=");
            String connId = name1[1];
            String[] name2 = ar1[1].split("=");
            int timeout = Integer.parseInt(name2[1]);
            input[i][0] = connId;/*from w  w w.j  a  v  a 2s. c  o m*/

            Date startTime = new Date();
            Date parsedDate = df.parse(startTime.toString());
            Date endTime = new Date(parsedDate.getTime() + (1 * timeout));
            input[i][1] = startTime.toString();
            input[i][2] = endTime.toString();
            i++;

            obj.put("status", "ok");
            try {
                Thread.currentThread().sleep(timeout);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
            pw.println(obj);
        } else if (url[0].equals("/serverStatus")) {
            Date now = new Date();
            long newDateTime = df.parse((new Date()).toString()).getTime();

            String result = "";
            JSONArray ja = new JSONArray();
            for (int j = 0; j < input.length; j++) {
                if (input[j][0] != null) {
                    Date end = df.parse(input[j][2]);
                    if (end.compareTo(now) > 0) {
                        long endDateTime = (df.parse(input[j][2])).getTime();
                        long diff = ((endDateTime - newDateTime) / 1000);
                        JSONObject obj1 = new JSONObject();
                        obj1.put(input[j][0], diff);
                        result += obj1;
                    }
                }
            }
            pw.println(result);
        } else {
            pw.println("Request not supported.");
        }
    } else if ((httpRequest.getHttpMethod().equals("PUT")) || (httpRequest.getHttpMethod().equals("POST"))) {
        if (httpRequest.getResourceURI().equals("/kill")) {
            boolean found = false;
            Date now = new Date();
            for (int j = 0; j < input.length; j++) {
                if (input[j][0] != null && input[j][0].equals(httpRequest.getBody())) {
                    Date end = df.parse(input[j][2]);
                    if (end.compareTo(now) > 0) {
                        input[j][2] = now.toString();
                        found = true;
                    }
                }
            }
            if (found) {
                obj.put("status", "killed");
            } else {
                obj.put("status", "Invalid connId " + httpRequest.getBody());
            }
            System.out.println(obj);
            pw.println(obj);
        } else {
            pw.println("Request not supported.");
        }
    }
    socket.close();
}

From source file:org.openmrs.module.pihmalawi.common.AppointmentInfo.java

/**
 * @return the days remaining until the appointment date. a negative number indicates that number of days overdue. null indicates no scheduled appointment found.
 *//*from   w w w.  ja v a2s .  com*/
public Integer getDaysToAppointment() {

    // No scheduled appointment
    if (nextScheduledDate == null || !currentlyEnrolled) {
        return null;
    }

    // No scheduled appointment since prevoius encounter
    if (lastEncounterDate != null && nextScheduledDate.compareTo(lastEncounterDate) <= 0) {
        return null;
    }

    Date today = DateUtil.getStartOfDay(effectiveDate);
    Date apptDate = DateUtil.getStartOfDay(nextScheduledDate);
    int multiplier = apptDate.compareTo(today); // If appt date is in the past, multiply by -1

    Date fromDate = (multiplier < 0 ? apptDate : today);
    Date toDate = (multiplier < 0 ? today : apptDate);

    Days days = Days.daysBetween(new DateTime(fromDate), new DateTime(toDate.getTime()));
    return days.getDays() * multiplier;
}

From source file:emcali.ami.control.webservice.IPTVAMIWebService.java

private JSONObject getData(JSONObject req, JSONObject resp) {
    Calendar cal = new GregorianCalendar();
    DateFormat dateformat = new SimpleDateFormat("dd-MM-YYYY");
    Date today = cal.getTime();//from   ww w  .j a  v a2  s .c o  m
    cal.add(Calendar.DAY_OF_MONTH, -11);
    Date tendaysago = cal.getTime();

    String telcoid = (String) req.get("suscriptor");
    TelcoInfoJpaController tijc = new TelcoInfoJpaController(utx, emf);
    TelcoInfo ti = tijc.findTelcoInfo(Long.parseLong(telcoid));

    try {
        JSONObject data = new JSONObject();
        JSONArray consumos = new JSONArray();
        AmyMedidores med = ti.getFkAmyMedidores();
        ComercialClientes cc = ti.getFkComercialClientes();
        List<AmyConsumos> ac = med.getAmyConsumosList();

        data.put("id_cliente", cc.getIdClientes());
        data.put("nombre_cliente", cc.getNombreClientes());
        data.put("direccion", cc.getDireccion());
        data.put("serial_medidor", med.getSerial());

        for (AmyConsumos amic : ac) {
            if (amic.getFkAmyInterval().getIntervalo().equals("Dia")) {
                Date fechacons = amic.getFechaConsumo();
                if ((fechacons.compareTo(tendaysago) > 0) && fechacons.before(today)) {
                    JSONObject consumo = new JSONObject();
                    consumo.put("consumo", amic.getConsumo());
                    consumo.put("fecha", dateformat.format(amic.getFechaConsumo()));
                    consumos.add(consumo);
                }
            }
        }
        data.put("consumos", consumos);
        resp.put("data", data);
    } catch (NullPointerException ex) {
        resp.put("message", "Invalid Telco user");
        resp.put("type", "error");
    }

    return resp;
}

From source file:edu.umd.cs.hcil.twitterreplay.ProducerTask.java

public void run() {
    System.out.println("Running with Current Time: " + mDateFormat.format(mCurrentTime));

    try {/*from  w  ww. ja va2  s  .  com*/
        // Find all tweets in the current interval
        List<String> messages = new ArrayList<String>();

        if (mNextItem == null || mNextItem.getLeft().compareTo(mCurrentTime) == 0) {

            System.out.println("Checking for more messages...");

            if (mNextItem != null) {
                messages.add(mNextItem.getRight());
            }

            for (String tweetJson : mInputReader) {
                try {
                    Date tweetTime = DateParser.getDateFromJson(tweetJson);

                    if (tweetTime.compareTo(mCurrentTime) < 0) {
                        System.err.println("Out of order tweet:");
                        System.err.println(tweetJson);

                        continue;
                        //                            throw new Error("Encountered Out-of-Order Tweet: " + tweetJson);
                    }

                    // Is this tweet the same as or AFTER the current time?
                    if (tweetTime.compareTo(mCurrentTime) == 0) {
                        messages.add(tweetJson);
                    } else {
                        mNextItem = new ImmutablePair<Date, String>(tweetTime, tweetJson);

                        break;
                    }
                } catch (JSONException ex) {
                    //                    LOGGER.log(Level.INFO, "JSON Exception: {0}", ex);
                    //                    LOGGER.log(Level.INFO, "Tweet JSON: {0}", tweetJson);
                } catch (ParseException ex) {
                    LOGGER.log(Level.SEVERE, "Parse Exception: {0}", ex);
                    LOGGER.log(Level.SEVERE, "Tweet JSON: {0}", tweetJson);
                }
            }
        } else {
            LOGGER.log(Level.INFO, "No messages during time: {0}", mDateFormat.format(mCurrentTime));
        }

        // Publish the messages for this interval to Kafka
        System.out.println("Message Count: " + messages.size());
        //        for ( String msg : messages ) {
        //            System.out.println(msg);
        //        }
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Unknown Exception: {0}", e);
    }

    mCurrentTime = mNextTime;
    mCalendar.add(mIntervalUnit, mInterval);
    mNextTime = mCalendar.getTime();
}