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.egov.works.services.AbstractEstimateService.java

public boolean checkForBudgetaryAppropriation(final FinancialDetail financialDetail,
        final String appropriationNumber) throws ValidationException {
    Long finyrId;//  w ww.  j a  v a  2  s  . c  om
    double budgApprAmnt;
    Date budgetAppDate = null;
    if (isPreviousYearApprRequired(financialDetail))
        budgetAppDate = getPreviousFinancialYear().getEndingDate();
    else
        budgetAppDate = new Date();
    // CFinancialYear
    // estimateDate_finYear=financialYearHibernateDAO.getFinYearByDate(financialDetail.getAbstractEstimate().getEstimateDate());
    final CFinancialYear budgetApprDate_finYear = financialYearHibernateDAO.getFinYearByDate(budgetAppDate);
    final List<Long> budgetheadid = new ArrayList<Long>();
    budgetheadid.add(financialDetail.getBudgetGroup().getId());
    boolean flag = false;

    finyrId = budgetApprDate_finYear.getId();
    if (budgetAppDate.compareTo(financialDetail.getAbstractEstimate().getEstimateDate()) >= 0)
        for (final MultiYearEstimate multiYearEstimate : financialDetail.getAbstractEstimate()
                .getMultiYearEstimates())
            if (multiYearEstimate != null
                    && multiYearEstimate.getFinancialYear().getId().compareTo(finyrId) == 0
                    && multiYearEstimate.getPercentage() > 0) {
                budgApprAmnt = financialDetail.getAbstractEstimate().getTotalAmount().getValue();
                final double percAmt = budgApprAmnt * multiYearEstimate.getPercentage() / 100;
                flag = checkConsumeEncumbranceBudget(financialDetail, finyrId, percAmt, budgetheadid,
                        appropriationNumber);
                if (flag != true)
                    return flag;
            }
    return flag;
}

From source file:skoa.helpers.Graficos.java

private Boolean estadisticas(Date d1, Date d2, String valor) {
    int dif = d1.compareTo(d2); //compara 2 fechas.
    float v;/* w ww .j a va  2s. com*/
    if (dif < 0 || dif == 0) { //d1 < d2 o d1=d2, estamos dentro del intervalo.
        valor = valor.substring(0, valor.indexOf(" ")); //Le quitamos la unidad de tiempo
        v = Float.parseFloat(valor);
        if (v > max)
            max = v;
        if (v < min)
            min = v;
        sum = sum + v; //suma de la media
        num++;
        return false;
    } else
        return true;
}

From source file:nl.b3p.commons.security.aselect.ASelectAuthorizationFilter.java

private boolean verifyCredentials(HttpServletRequest request, String rid, String credentials)
        throws ServletException, ASelectAuthorizationException {

    Map params = new Hashtable();
    params.put("request", "verify_credentials");
    params.put("rid", rid);
    params.put("aselect_credentials", credentials);

    Map asResponse = null;/*www.ja v  a  2  s . c  o  m*/
    try {
        asResponse = client.performRequest(params);
    } catch (IOException e) {
        throw new ServletException(e);
    }

    String asResult = (String) asResponse.get("result_code");
    String asTicket = (String) asResponse.get("ticket");
    String asTicketExpTime = (String) asResponse.get("ticket_exp_time");
    String asUid = (String) asResponse.get("uid");
    String asOrganization = (String) asResponse.get("organization");
    String asAuthSPLevel = (String) asResponse.get("authsp_level");
    String asAuthSP = (String) asResponse.get("authsp");
    String asAttributes = (String) asResponse.get("attributes");

    if (!ASELECT_OK.equals(asResult)) {
        /* Indien user error naar errorpage met melding ala
         *  "Uw sessie is verlopen of ongeldig of U heeft te lang gewacht
         *   met inloggen. Probeer het opnieuw."
         * Eventueel met link of met refresh na aantal seconden
         *
         * TODO bij request.getSession().isNew() error met "Uw browser moet
         * cookies accepteren" oid
         *
         * Bij andere errors ServletException
         */
        log.info("Received error code \"" + asResult + "\" from A-Select when verifying credentials (from IP: "
                + request.getRemoteHost() + ")");
        if (isUserError(asResult)) {
            /* FIXME foutmelding afhankelijk van result code */
            return false;
        } else {
            throw new ServletException("A-Select communication error");
        }
    } else {
        Date startTime, expTime;

        /* De Agent geeft ticket_start_time mee maar de Server niet omdat
         * bij de server api je zelf bij moet houden wanneer het ticket is
         * verlopen zoals de agent doet.
         *
         * Een tekortkoming van het A-Select protocol is dat indien de systeemtijd
         * van de A-Select server en de client niet overeenkomen het ticket
         * meteen expired of de duur van het ticket verkeerd is (te  kort
         * danwel te lang).
         *
         * Nou is in een webapplicatie omgeving de systeemtijd van de server
         * die de echte eindtijd van het ticket bepaalt natuurlijk wel te
         * synchronizeren met die van de A-Select server die de originele
         * eindtijd van het ticket bepaalt.
         */

        if (api == ASELECT_API_AGENT) {
            startTime = new Date(Long.parseLong((String) asResponse.get("ticket_start_time")));
        } else {
            startTime = new Date();
        }

        try {
            expTime = new Date(Long.parseLong(asTicketExpTime));

            log.debug("Ticket start date/time:      " + startTime);
            log.debug("Ticket expiration date/time: " + expTime);

            if (startTime.compareTo(expTime) > 0) {
                throw new ServletException("A-Select server specified ticket expiration time in the past");
            }

        } catch (NumberFormatException nfe) {
            log.error("invalid date received from A-Select server", nfe);
            throw new ServletException("A-Select communication error");
        }

        ASelectTicket ticket;

        if (api == ASELECT_API_AGENT) {
            ticket = new ASelectAgentTicket(asTicket, appId, startTime, expTime, asUid, asOrganization,
                    asAuthSPLevel, asAuthSP, asAttributes, (ASelectAgentClient) client);
        } else {
            /* api == ASELECT_API_SERVER */
            // TODO impl deze ticket, die adv expTime verify() implementeert
            ticket = null;
            //ticket = new ASelectServerTicket(asTicket, startTime, expTime,
            //    asUid, asOrganization, asAuthSPLevel, asAuthSP, asAttributes);
        }
        ticket.putOnSession(request.getSession());
        return true;
    }
}

From source file:com.krawler.spring.crm.common.crmManagerDAOImpl.java

/**
 * To convert a date and time selected separately by user into corresponding combined datetime
 * from users selected timezone to systems timezone
 *
 * The first step is to keep track of the time difference in order to change the date if required.
 * Two time only objects dtold and dtcmp are created for this purpose.
 *
 * The date passed and the time passed that are in system timezone are formatted without
 * timezone and then parsed into the required timezone and then the time values are set
 * back to the date value sent./*from ww w  .  j  a v  a2 s .co m*/
 *
 **/
public Date converttz(String timeZoneDiff, Date dt, String time) {
    Calendar cal = Calendar.getInstance();
    try {
        if (timeZoneDiff == null || timeZoneDiff.isEmpty()) {
            timeZoneDiff = "-7:00";
        }
        String val;
        SimpleDateFormat sdf = new SimpleDateFormat("HHmm 'Hrs'");
        Date dtold = sdf.parse("0000 Hrs");
        if (!time.endsWith("Hrs")) {
            sdf = new SimpleDateFormat("hh:mm a");
            dtold = sdf.parse("00:00 AM");
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
        sdf2.setTimeZone(TimeZone.getTimeZone("GMT" + timeZoneDiff)); // Setting the timezone passed

        Date dt1 = sdf.parse(time); // Setting the passed time to the date object in system timezone

        sdf.setTimeZone(TimeZone.getTimeZone("GMT" + timeZoneDiff)); // Setting the timezone passed
        Date dtcmp = sdf.parse(time); // Parsing the time to timezone using passed values
        dt1.setMonth(dt.getMonth()); // Setting the date values sent to the system time only value
        dt1.setDate(dt.getDate());
        dt1.setYear(dt.getYear());
        dt1 = sdf2.parse(sdf1.format(dt1)); // Parsing datetime into required timezone
        dt.setHours(dt1.getHours()); // Setting the time values into the sent date
        dt.setMinutes(dt1.getMinutes());
        dt.setSeconds(0);
        cal.setTime(dt);
        if (dtcmp.compareTo(dtold) < 0) { // Comparing for time value change
            cal.add(Calendar.DATE, -1); //  in order to change the date accordingly
        }
        dtold.setDate(2);
        if (dtcmp.compareTo(dtold) > 0 || dtcmp.compareTo(dtold) == 0) {
            cal.add(Calendar.DATE, 1);
        }

    } catch (ParseException ex) {
        System.out.println(ex);
    } finally {
        return cal.getTime();
    }
}

From source file:grupob.TipoProceso.java

private boolean verificaFechas(Date datei1, Date datei2, Date datef1, Date datef2) {
    Calendar cal = Calendar.getInstance();
    Date dateActual = cal.getTime();
    if (datei1.compareTo(dateActual) < 0 || datei2.compareTo(dateActual) < 0 || datef1.compareTo(dateActual) < 0
            || datef2.compareTo(dateActual) < 0) {
        JOptionPane.showMessageDialog(null, "Error: Los valores de la fecha deben ser superiores a hoy");
        return false;
    }//from  w w w. j  a  v  a  2s . c o m
    if (datei1.compareTo(datef2) > 0 || datei1.compareTo(datei2) > 0 || datei1.compareTo(datef1) > 0) {
        JOptionPane.showMessageDialog(null, "Error: Revise el orden de los valores ingresados");
        return false;
    }
    if (datei2.compareTo(datei1) < 0 || datei2.compareTo(datef1) < 0 || datei2.compareTo(datef2) > 0) {
        JOptionPane.showMessageDialog(null, "Error: Revise el orden de los valores ingresados");
        return false;
    }
    if (datef1.compareTo(datei1) < 0 || datef1.compareTo(datei2) > 0 || datef1.compareTo(datef2) > 0) {
        JOptionPane.showMessageDialog(null, "Error: Revise el orden de los valores ingresados");
        return false;
    }
    return true;
}

From source file:com.openbravo.pos.sales.restaurant.JRetailTicketsBagRestaurantMap.java

public void moveTicket() {
    try {/*  ww w  .j a v a 2  s.  c om*/
        logger.info("Move Ticket Action Table name: " + m_panelticket.getActiveTicket().getTableName());

        String currentUpdated = m_dateformat.format(m_panelticket.getActiveTicket().getObjectUpdateDate()) + " "
                + m_dateformattime.format(m_panelticket.getActiveTicket().getObjectUpdateDate());
        String dbUpdated = dlReceipts.getUpdatedTime(m_panelticket.getActiveTicket().getPlaceId(),
                m_panelticket.getActiveTicket().getSplitSharedId());
        Date currentUpdatedDate = DateFormats.StringToDateTime(currentUpdated);
        Date dbUpdatedDate = DateFormats.StringToDateTime(dbUpdated);
        if (dbUpdated.equals(null) || dbUpdated.equals("")) {
            logger.info("This Bill is no longer exist");
            showMessage(this, "This Bill is no longer exist");
        } else if (dbUpdatedDate.compareTo(currentUpdatedDate) > 0) {
            try {
                logger.info("The Table is being accessed by another User!Cannot update the bill");
                // showMessage(this, "The Table is being accessed by another User!Cannot update the bill");
                //added in testing
                RetailTicketInfo dbticket = dlReceipts.getRetailSharedTicketSplit(
                        m_panelticket.getActiveTicket().getPlaceId(),
                        m_panelticket.getActiveTicket().getSplitSharedId());
                dbticket.setObjectUpdateDate(dbUpdatedDate);
                for (int index = 0; index < m_panelticket.getActiveTicket().getLinesCount(); index++) {
                    if (m_panelticket.getActiveTicket().getLine(index).getIsKot() == 0) {
                        m_panelticket.getActiveTicket().getLine(index)
                                .setDiscount(Double.parseDouble(dbticket.getRate()) * 100);
                        dbticket.addLine(m_panelticket.getActiveTicket().getLine(index));
                    }
                }
                JRetailBufferWindow.showMessage(this);
                m_panelticket.setRetailActiveTicket(dbticket, dbticket.getTableName());
            } catch (BasicException ex) {
                Logger.getLogger(JRetailTicketsBagRestaurantMap.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {

            //adding condition for move table not to allow if the table having zero line items
            if (m_panelticket.getActiveTicket().getLinesCount() == 0) {
                showMessage(this, "Table cannot be moved because it has no items");
            } //Checking whether bill is printed
            else if ((m_panelticket.getActiveTicket().isPrinted())
                    && !(m_panelticket.getActiveTicket().isListModified())) {
                showMessage(this, "Table cannot be moved because bill is printed");
            } else {
                //checking any kot item present?
                int kotcount = 0;
                for (int k = 0; k < m_panelticket.getActiveTicket().getLinesCount(); k++) {
                    if (m_panelticket.getActiveTicket().getLine(k).getIsKot() == 1) {
                        kotcount = 1;
                        break;
                    }
                }
                // if non kot bill then table cannot be moved
                if (kotcount == 0) {
                    showMessage(this, "Table cannot be moved because it has non kot items");
                } else {
                    //removing all non kot items while moving the table
                    int i = 0;
                    while (i < m_panelticket.getActiveTicket().getLinesCount()) {
                        if (m_panelticket.getActiveTicket().getLine(i).getIsKot() == 0) {
                            m_panelticket.getActiveTicket().removeLine(i);
                            i = 0;
                        } else {
                            i++;
                        }
                    }
                    m_panelticket.getActiveTicket().refreshTxtFields(0);
                    if (m_PlaceCurrent != null) {
                        try {//Checking whether we are moving splitted bill
                            if (m_panelticket.getActiveTicket().getSplitValue().equals("Split")) {
                                movedSplitTable = true;
                                m_panelticket.getActiveTicket().setSplitValue("");
                            }
                            //Saving into a variable move table id
                            SplitTableMoveId = m_panelticket.getActiveTicket().getSplitSharedId();
                            dlReceipts.updateSharedTicket(m_PlaceCurrent.getId(),
                                    m_panelticket.getActiveTicket());
                        } catch (BasicException e) {
                            logger.info("move table exception " + e.getMessage());
                            new MessageInf(e).show(this);
                        }

                        // me guardo el ticket que quiero copiar.
                        m_PlaceClipboard = m_PlaceCurrent;
                        customer = null;
                        m_PlaceCurrent = null;
                    }

                    printState();
                    m_panelticket.setRetailActiveTicket(null, null);
                    loadTickets();
                    startTimer();
                }
            }
        }
    } catch (BasicException ex) {
        Logger.getLogger(JRetailTicketsBagRestaurantMap.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

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

        if ((startDate != null) && (filterFinishDate.getRawValue() != null)
                && (startDate.compareTo((Date) filterFinishDate.getRawValue()) > 0)) {

            throw new WrongValueException(comp, _("must be lower than end date"));
        }//from  w  w w  .  j  a  v  a2s.  c  o m
    };
}

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

/**
 * Operations to filter the orders by multiple filters.
 *///from  w w w  . j a v a2  s. co  m

public Constraint checkConstraintFinishDate() {
    return (comp, value) -> {
        Date finishDate = (Date) value;

        if ((finishDate != null) && (filterStartDate.getRawValue() != null)
                && (finishDate.compareTo((Date) filterStartDate.getRawValue()) < 0)) {

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

From source file:org.kuali.coeus.common.budget.impl.calculator.SalaryCalculator.java

/**
 * -Uses sorted Budget Persons list and Inflation rates list to create salary breakup periods, each period consisting of a
 * SalaryDetails -Call calculate method of each bean to calculate salary
 * //from   w  ww. j  a v  a  2  s . c  o m
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private QueryList<SalaryDetails> createSalBreakupIntervals() {
    QueryList combinedList = new QueryList();
    combinedList.addAll(filterBudgetPersons());
    combinedList.addAll(filterInflationRates());
    combinedList.sort("sortableDate");
    if (isAnniversarySalaryDateEnabled()) {
        combinedList = processAnniversarySalaryDateInflationRates(combinedList);
    }
    QueryList<SalaryDetails> breakUpIntervals = new QueryList<SalaryDetails>();
    BudgetPerson budgetPerson = null;
    BudgetRate budgetRate = null;
    BudgetRate prevBudgetProposalRate = null;
    Date tempStartDate = startDate;
    Date tempEndDate = endDate;
    Date rateChangeDate = null;
    SalaryDetails salaryDetails;
    SalaryDetails prevSalaryDetails = new SalaryDetails();
    for (int index = 0; index < combinedList.size(); index++) {
        Object changedObject = combinedList.get(index);
        boolean personFlag = changedObject instanceof BudgetPerson;
        if (personFlag) {
            budgetPerson = (BudgetPerson) changedObject;
            rateChangeDate = budgetPerson.getStartDate();
            prevSalaryDetails.setActualBaseSalary(budgetPerson.getCalculationBase());
            if (budgetPerson.getAppointmentType() == null) {
                budgetPerson.refreshReferenceObject("appointmentType");
            }
            prevSalaryDetails.setWorkingMonths(budgetPerson.getAppointmentType().getDuration());

        } else {
            budgetRate = (BudgetRate) changedObject;
            rateChangeDate = budgetRate.getStartDate();
        }
        if (budgetPerson == null) {
            continue;
        }
        int compareDateChange = rateChangeDate.compareTo(tempStartDate);
        if (compareDateChange > 0) {
            Calendar rateChangeCal = dateTimeService.getCalendar(rateChangeDate);
            rateChangeCal.add(Calendar.DATE, -1);
            tempEndDate = rateChangeCal.getTime();
            Boundary boundary = new Boundary(tempStartDate, tempEndDate);
            salaryDetails = new SalaryDetails();
            salaryDetails.setBoundary(boundary);
            if (!personFlag && budgetRate != null) {
                salaryDetails.setActualBaseSalary(getPrevSalaryBase(budgetPerson, boundary));
                if (prevBudgetProposalRate != null
                        && budgetPerson.getEffectiveDate().before(prevBudgetProposalRate.getStartDate())
                        && budgetPerson.getEffectiveDate().before(boundary.getStartDate())
                        && prevBudgetProposalRate.getStartDate().before(boundary.getEndDate())
                        && (prevBudgetProposalRate.getStartDate().equals(boundary.getStartDate())
                                || budget.getBudgetPeriods().get(0).getEndDate().before(startDate))) {
                    salaryDetails.calculateActualBaseSalary(budgetRate.getApplicableRate());
                } else {
                    if (budgetRate != null && budgetPerson.getEffectiveDate().before(budgetRate.getStartDate())
                            && budgetPerson.getEffectiveDate().before(startDate)
                            && budgetRate.getStartDate().before(boundary.getEndDate())
                            && (budgetRate.getStartDate().compareTo(startDate) <= 0
                                    || budget.getBudgetPeriods().get(0).getEndDate().before(startDate))) {
                        salaryDetails.calculateActualBaseSalary(budgetRate.getApplicableRate());
                    }
                }
                salaryDetails.setWorkingMonths(prevSalaryDetails.getWorkingMonths());
                salaryDetails.setAltBudgetPerson(getSameJobPerson(boundary, budgetPerson));
            }
            if (personFlag && budgetPerson != null) {
                salaryDetails.setActualBaseSalary(budgetPerson.getCalculationBase());
                salaryDetails.setWorkingMonths(budgetPerson.getAppointmentType().getDuration());
                salaryDetails.setAltBudgetPerson(getSameJobPerson(boundary, budgetPerson));
            }
            if (budgetPerson.getStartDate().compareTo(tempStartDate) <= 0) {
                breakUpIntervals.add(salaryDetails);
            }
            prevBudgetProposalRate = budgetRate;
            prevSalaryDetails = salaryDetails;
            tempStartDate = rateChangeDate;
        }
    }
    salaryDetails = new SalaryDetails();
    Boundary boundary = new Boundary(tempStartDate, endDate);
    salaryDetails = new SalaryDetails();
    salaryDetails.setBoundary(boundary);
    if (budgetRate != null && budgetPerson != null
            && budgetPerson.getEffectiveDate().before(budgetRate.getStartDate())) {
        salaryDetails.calculateActualBaseSalary(budgetRate.getApplicableRate());
        salaryDetails.setWorkingMonths(prevSalaryDetails.getWorkingMonths());
    }
    if (budgetPerson != null) {
        salaryDetails.setActualBaseSalary(getPrevSalaryBase(budgetPerson, boundary));
        populateAppointmentType(budgetPerson);
        BudgetPerson newBudgetPerson = getBudgetPersonApplied(budgetPerson, boundary);
        if (budgetRate != null && ((newBudgetPerson == null
                && budgetPerson.getEffectiveDate().before(budgetRate.getStartDate()))
                || (newBudgetPerson != null
                        && newBudgetPerson.getEffectiveDate().before(budgetRate.getStartDate())))) {
            salaryDetails.calculateActualBaseSalary(budgetRate.getApplicableRate());
        }

        if (newBudgetPerson != null) {
            newBudgetPerson.refreshReferenceObject("appointmentType");
            salaryDetails.setWorkingMonths(newBudgetPerson.getAppointmentType() == null ? DEFAULT_WORKING_MONTHS
                    : newBudgetPerson.getAppointmentType().getDuration());
        } else {
            salaryDetails.setWorkingMonths(budgetPerson.getAppointmentType() == null ? DEFAULT_WORKING_MONTHS
                    : budgetPerson.getAppointmentType().getDuration());
        }
        salaryDetails.setAltBudgetPerson(getSameJobPerson(boundary, budgetPerson));
    }
    breakUpIntervals.add(salaryDetails);
    return breakUpIntervals;

}

From source file:org.libreplan.web.calendars.BaseCalendarEditionController.java

public void updateException() {
    Combobox exceptionTypes = (Combobox) window.getFellow("exceptionTypes");
    CalendarExceptionType type = exceptionTypes.getSelectedItem().getValue();

    Datebox dateboxStartDate = (Datebox) window.getFellow("exceptionStartDate");
    Date startDate = dateboxStartDate.getValue();

    if (startDate == null) {
        throw new WrongValueException(dateboxStartDate, _("You should select a start date for the exception"));
    } else {/*w ww . ja  va 2 s.com*/
        Clients.clearWrongValue(dateboxStartDate);
    }

    Datebox dateboxEndDate = (Datebox) window.getFellow("exceptionEndDate");
    Date endDate = dateboxEndDate.getValue();

    if (endDate == null) {
        throw new WrongValueException(dateboxEndDate, _("Please, select an End Date for the Exception"));
    } else {
        Clients.clearWrongValue(dateboxEndDate);
    }

    if (startDate.compareTo(endDate) > 0) {
        throw new WrongValueException(dateboxEndDate,
                _("Exception end date should be greater or equals than start date"));
    } else {
        Clients.clearWrongValue(dateboxEndDate);
    }

    Capacity capacity = capacityPicker.getValue();

    baseCalendarModel.updateException(type, LocalDate.fromDateFields(startDate),
            LocalDate.fromDateFields(endDate), capacity);

    reloadDayInformation();
}