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.openmrs.module.pihmalawi.reporting.definition.cohort.evaluator.RelativeDateCohortDefinitionEvaluator.java

public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context)
        throws EvaluationException {
    RelativeDateCohortDefinition cd = (RelativeDateCohortDefinition) cohortDefinition;

    Cohort c = new Cohort();

    PatientData data1 = patientDataService.evaluate(cd.getEarlierDateDefinition(), context);
    PatientData data2 = patientDataService.evaluate(cd.getLaterDateDefinition(), context);

    Set<Integer> allPats = new HashSet<Integer>(data1.getData().keySet());
    allPats.addAll(data2.getData().keySet());

    RangeComparator operator = cd.getDifferenceOperator();

    for (Integer pId : allPats) {
        Date d1 = (Date) data1.getData().get(pId);
        Date d2 = (Date) data2.getData().get(pId);

        boolean includePatient = false;
        if (d1 == null) {
            if (cd.isPassIfDate1Null()) {
                includePatient = true;//from w  w w .ja  v a  2 s. c o m
            }
        } else if (d2 == null) {
            if (cd.isPassIfDate2Null()) {
                includePatient = true;
            }
        } else {
            Integer diffNum = cd.getDifferenceNumber();
            DurationUnit diffUnit = cd.getDifferenceUnit();
            if (diffNum == null) {
                int comparison = d1.compareTo(d2);
                if (comparison < 0) {
                    if (operator == RangeComparator.LESS_THAN || operator == RangeComparator.LESS_EQUAL) {
                        includePatient = true;
                    }
                } else if (comparison > 0) {
                    if (operator == RangeComparator.GREATER_THAN || operator == RangeComparator.GREATER_EQUAL) {
                        includePatient = true;
                    }
                } else {
                    if (operator == RangeComparator.EQUAL || operator == RangeComparator.LESS_EQUAL
                            || operator == RangeComparator.GREATER_EQUAL) {
                        includePatient = true;
                    }
                }
            } else {
                Date adjustedD1 = DateUtil.adjustDate(d1, diffNum, diffUnit);
                int comparison = adjustedD1.compareTo(d2);
                if (comparison < 0) { // This means that more than the configured units has gone by
                    if (operator == RangeComparator.GREATER_THAN || operator == RangeComparator.GREATER_EQUAL) {
                        includePatient = true;
                    }
                } else if (comparison > 0) {
                    if (operator == RangeComparator.LESS_THAN || operator == RangeComparator.LESS_EQUAL) {
                        includePatient = true;
                    }
                } else {
                    if (operator == RangeComparator.EQUAL || operator == RangeComparator.LESS_EQUAL
                            || operator == RangeComparator.GREATER_EQUAL) {
                        includePatient = true;
                    }
                }
            }
        }

        if (includePatient) {
            c.addMember(pId);
        }
    }

    return new EvaluatedCohort(c, cd, context);
}

From source file:fr.hoteia.qalingo.core.domain.Customer.java

public CustomerCredential getCurrentCredential() {
    if (credentials != null) {
        List<CustomerCredential> sortedObjects = new LinkedList<CustomerCredential>(credentials);
        Collections.sort(sortedObjects, new Comparator<CustomerCredential>() {
            @Override/*from  ww w .ja  va  2  s.com*/
            public int compare(CustomerCredential o1, CustomerCredential o2) {
                if (o1 != null && o2 != null) {
                    Date order1 = o1.getDateCreate();
                    Date order2 = o2.getDateCreate();
                    if (order1 != null && order2 != null) {
                        return order1.compareTo(order2);
                    } else {
                        return o1.getId().compareTo(o2.getId());
                    }
                }
                return 0;
            }
        });
        return sortedObjects.get(0);
    }
    return null;
}

From source file:com.aurel.track.item.ItemBL.java

public static List<TWorkItemBean> getChildren(Integer workItemID, Integer personID) {
    if (workItemID == null) {
        return new LinkedList<TWorkItemBean>();
    }/*from   w w w. j a  v  a  2  s .co  m*/
    List<TWorkItemBean> workItemList = workItemDAO.getChildren(workItemID);
    if (workItemList == null || workItemList.isEmpty()) {
        return new LinkedList<TWorkItemBean>();
    }
    int[] workItemIDs = GeneralUtils
            .createIntArrFromIntegerList(GeneralUtils.createIntegerListFromBeanList(workItemList));
    List<TWorkItemBean> workItemBeans = LoadItemIDListItems.getWorkItemBeansByWorkItemIDs(workItemIDs, personID,
            false, false, false);
    Collections.sort(workItemBeans, new Comparator<TWorkItemBean>() {
        public int compare(TWorkItemBean workItemBean1, TWorkItemBean workItemBean2) {
            Date startDate1 = workItemBean1.getStartDate();
            if (startDate1 == null) {
                startDate1 = workItemBean1.getCreated();
            }
            Date startDate2 = workItemBean2.getStartDate();
            if (startDate2 == null) {
                startDate2 = workItemBean2.getCreated();
            }
            return startDate1.compareTo(startDate2);
        }
    });
    return workItemBeans;
}

From source file:org.exoplatform.platform.portlet.juzu.calendar.CalendarPortletController.java

@Ajax
@Resource/*from   ww  w .  jav a  2 s  .c om*/
public Response.Content calendarHome() throws Exception {

    displayedCalendar.clear();
    displayedCalendarMap.clear();
    tasksDisplayedList.clear();
    eventsDisplayedList.clear();
    String date_act = null;
    String username = CalendarPortletUtils.getCurrentUser();
    Locale locale = Util.getPortalRequestContext().getLocale();
    String dp = formatDate(locale);
    DateFormat d = new SimpleDateFormat(dp);
    DateFormat dTimezone = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    dTimezone.setCalendar(CalendarPortletUtils.getCurrentCalendar());
    Long date = new Date().getTime();
    int clickNumber = Integer.parseInt(nbclick);
    if (clickNumber != 0)
        date = incDecJour(date, clickNumber);
    Date currentTime = new Date(date);
    // Get Calendar object set to the date and time of the given Date object
    Calendar cal = CalendarPortletUtils.getCurrentCalendar();
    cal.setTime(currentTime);

    // Set time fields to zero
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    // Put it back in the Date object
    currentTime = cal.getTime();
    date_act = d.format(currentTime);
    Date comp = currentTime;
    String defaultCalendarLabel = "Default";
    String dateLabel = "";
    try {
        ResourceBundle rs = ResourceBundle.getBundle("locale/portlet/calendar/calendar", locale);
        defaultCalendarLabel = EntityEncoder.FULL.encode(rs.getString("UICalendars.label.defaultCalendarId"));
        if (clickNumber == 0)
            dateLabel = rs.getString("today.label") + ": ";
        else if (clickNumber == -1)
            dateLabel = rs.getString("yesterday.label") + ": ";
        else if (clickNumber == 1)
            dateLabel = rs.getString("tomorrow.label") + ": ";
        else
            dateLabel = "";
    } catch (MissingResourceException ex) {
        if (clickNumber == 0)
            dateLabel = "today.label" + ": ";
        else if (clickNumber == -1)
            dateLabel = "yesterday.label" + ": ";
        else if (clickNumber == 1)
            dateLabel = "tomorrow.label" + ": ";
        else
            dateLabel = "";
    }

    EntityEncoder.FULL.encode(dateLabel);
    dateLabel = new StringBuffer(dateLabel).append(date_act).toString();
    if (nonDisplayedCalendarList == null) {
        SettingValue settingNode = settingService_.get(Context.USER, Scope.APPLICATION,
                CalendarPortletUtils.HOME_PAGE_CALENDAR_SETTINGS);
        if ((settingNode != null) && (settingNode.getValue().toString().split(":").length == 2)) {
            nonDisplayedCalendarList = settingNode.getValue().toString().split(":")[1].split(",");
        }
    }
    List<CalendarEvent> userEvents = getEvents(username, cal);
    if ((userEvents != null) && (!userEvents.isEmpty())) {
        Iterator itr = userEvents.iterator();
        while (itr.hasNext()) {
            CalendarEvent event = (CalendarEvent) itr.next();
            Date from = d.parse(dTimezone.format(event.getFromDateTime()));
            Date to = d.parse(dTimezone.format(event.getToDateTime()));
            if ((event.getEventType().equals(CalendarEvent.TYPE_EVENT))
                    && (from.compareTo(d.parse(dTimezone.format(comp))) <= 0)
                    && (to.compareTo(d.parse(dTimezone.format(comp))) >= 0)) {
                if (!CalendarPortletUtils.contains(nonDisplayedCalendarList, event.getCalendarId())) {
                    org.exoplatform.calendar.service.Calendar calendar = calendarService_
                            .getUserCalendar(username, event.getCalendarId());
                    if (calendar == null) {
                        calendar = calendarService_.getGroupCalendar(event.getCalendarId());
                    }
                    if (calendar.getGroups() == null) {
                        if (calendar.getId().equals(Utils.getDefaultCalendarId(username))
                                && calendar.getName().equals(NewUserListener.defaultCalendarName)) {
                            calendar.setName(defaultCalendarLabel);
                        }
                    }
                    eventsDisplayedList.add(event);
                    if (!displayedCalendarMap.containsKey(calendar.getId())) {
                        displayedCalendarMap.put(calendar.getId(), calendar);
                        displayedCalendar.add(calendar);
                    }
                }
            } else if ((event.getEventType().equals(CalendarEvent.TYPE_TASK))
                    && (((from.compareTo(comp) <= 0) && (to.compareTo(comp) >= 0))
                            || ((event.getEventState().equals(CalendarEvent.NEEDS_ACTION))
                                    && (to.compareTo(comp) < 0)))) {
                tasksDisplayedList.add(event);
            }
        }
        Collections.sort(eventsDisplayedList, eventsComparator);
        Collections.sort(tasksDisplayedList, tasksComparator);
    }
    return calendar.with().set("displayedCalendar", displayedCalendar)
            .set("calendarDisplayedMap", displayedCalendarMap).set("eventsDisplayedList", eventsDisplayedList)
            .set("tasksDisplayedList", tasksDisplayedList).set("date_act", dateLabel).ok()
            .withCharset(Tools.UTF_8);
}

From source file:it.av.es.service.impl.OrderServiceHibernate.java

/**
 * {@inheritDoc}//from w  ww . jav  a  2s.  c  om
 */
@Override
public List<Date> getDates(User user, Project project) {
    Set<Date> d = new HashSet<Date>();
    Collection<Order> list = get(user, project, null, null, null, false, 0, 0, Order.CREATIONTIME_FIELD, false);
    for (Order o : list) {
        d.add(DateUtils.truncate(o.getCreationTime(), Calendar.DAY_OF_MONTH));
    }
    ArrayList<Date> dates = new ArrayList<Date>(d);
    Collections.sort(dates, new Comparator<Date>() {
        @Override
        public int compare(Date s1, Date s2) {
            return s2.compareTo(s1);
        }
    });
    return dates;
}

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

String CompareTime(String a, String b, String operator) throws ParseException {

    if (a == null) {
        return b;
    }//from  www  .j  a v a 2  s. c o  m

    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);
    }

    switch (operator) {
    case "01":
        return ((x.compareTo(y) <= 0) ? a : b);
    case "04":
        return ((x.compareTo(y) >= 0) ? a : b);
    default:
        throw new IllegalArgumentException("Operator " + operator + " not fould in control!");
    }
}

From source file:org.openmrs.api.db.hibernate.HibernateEncounterDAO.java

/**
 * @see org.openmrs.api.db.EncounterDAO#getEncountersByVisitsAndPatient(org.openmrs.Patient,
 *      boolean, java.lang.String, java.lang.Integer, java.lang.Integer)
 *//*from   w  ww. j  av  a  2 s  .c  om*/
@Override
public List<Encounter> getEncountersByVisitsAndPatient(Patient patient, boolean includeVoided, String query,
        Integer start, Integer length) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Encounter.class);
    addEncountersByPatientCriteria(criteria, patient, includeVoided, query);

    @SuppressWarnings("unchecked")
    List<Encounter> encounters = criteria.list();

    criteria = sessionFactory.getCurrentSession().createCriteria(Visit.class);
    addEmptyVisitsByPatientCriteria(criteria, patient, includeVoided, query);

    @SuppressWarnings("unchecked")
    List<Visit> emptyVisits = criteria.list();

    if (!emptyVisits.isEmpty()) {
        for (Visit emptyVisit : emptyVisits) {
            Encounter mockEncounter = new Encounter();
            mockEncounter.setVisit(emptyVisit);
            encounters.add(mockEncounter);
        }

        Collections.sort(encounters, new Comparator<Encounter>() {

            @Override
            public int compare(Encounter o1, Encounter o2) {
                Date o1Date = (o1.getVisit() != null) ? o1.getVisit().getStartDatetime()
                        : o1.getEncounterDatetime();
                Date o2Date = (o2.getVisit() != null) ? o2.getVisit().getStartDatetime()
                        : o2.getEncounterDatetime();
                return o2Date.compareTo(o1Date);
            }
        });
    }

    if (start == null) {
        start = 0;
    }
    if (length == null) {
        length = encounters.size();
    }
    int end = start + length;
    if (end > encounters.size()) {
        end = encounters.size();
    }

    return encounters.subList(start, end);
}

From source file:it.av.es.service.impl.OrderServiceHibernate.java

/**
 * {@inheritDoc}/*w w  w .j a  va 2s.c  o m*/
 */
@Override
public List<Date> getDeliveredDates(User user, Project project) {
    Set<Date> d = new HashSet<Date>();
    Collection<Order> list = get(user, project, null, null, null, false, 0, 0, Order.DELIVEREDTIME_FIELD,
            false);
    for (Order o : list) {
        if (o.getDeliveredTime() != null) {
            d.add(DateUtils.truncate(o.getDeliveredTime(), Calendar.DAY_OF_MONTH));
        }
    }
    ArrayList<Date> dates = new ArrayList<Date>(d);
    Collections.sort(dates, new Comparator<Date>() {
        @Override
        public int compare(Date s1, Date s2) {
            return s2.compareTo(s1);
        }
    });
    return dates;
}

From source file:com.github.amsacode.predict4java.PassPredictor.java

/**
 * Gets a list of SatPassTime/*from  w w  w .ja  v a2s . co m*/
 * 
 * @param start
 *            Date
 * 
 *            newTLE = true; validateData();
 * @param end
 *            Date
 * @param firstAosLimit
 *            in hours
 * @return List<SatPassTime>
 * @throws SatNotFoundException
 * @throws InvalidTleException
 */
public List<SatPassTime> getPasses(final Date start, final int hoursAhead, final boolean windBack)
        throws SatNotFoundException {

    this.iterationCount = 0;

    boolean windBackTime = windBack;

    final List<SatPassTime> passes = new ArrayList<SatPassTime>();

    Date trackStartDate = start;
    final Date trackEndDate = new Date(start.getTime() + (hoursAhead * 60L * 60L * 1000L));

    Date lastAOS;

    int count = 0;

    do {
        if (count > 0) {
            windBackTime = false;
        }
        final SatPassTime pass = nextSatPass(trackStartDate, windBackTime);
        lastAOS = pass.getStartTime();
        passes.add(pass);
        trackStartDate = new Date(pass.getEndTime().getTime() + (threeQuarterOrbitMinutes() * 60L * 1000L));
        count++;
    } while (lastAOS.compareTo(trackEndDate) < 0);

    return passes;
}

From source file:de.xwic.appkit.core.dao.AbstractDAO.java

public IEntity findCorrectVersionForEntityRelation(IEntity mainObject, IEntity relationObject) {
    if (mainObject == null) {
        throw new IllegalArgumentException("Parameter is null in: " + getClass().getName());
    }//w  w w .  j  a  va 2  s  .  c om

    if (relationObject == null) {
        return null;
    }

    // get the actual date of the main object
    Date actualVersionDate = mainObject.getLastModifiedAt();

    // find the dao for the relation object to check
    DAO relDao = DAOSystem.findDAOforEntity(relationObject.type());

    // get all history versions for the main object
    List<?> allHisObjs = relDao.getHistory(relationObject);

    IEntity element = null;
    for (Iterator<?> iter = allHisObjs.iterator(); iter.hasNext();) {
        IEntity locObj = (IEntity) iter.next();
        Date locDate = locObj.getLastModifiedAt();
        // if the date is lesser than the actual date, the element might be
        // a candidate...
        if (locDate.compareTo(actualVersionDate) < 0) {
            element = locObj;
        } else {
            // more -> get out
            break;
        }
    }

    return element == null ? relationObject : element;
}