Example usage for org.joda.time Days daysBetween

List of usage examples for org.joda.time Days daysBetween

Introduction

In this page you can find the example usage for org.joda.time Days daysBetween.

Prototype

public static Days daysBetween(ReadablePartial start, ReadablePartial end) 

Source Link

Document

Creates a Days representing the number of whole days between the two specified partial datetimes.

Usage

From source file:com.blackducksoftware.integration.jira.task.JiraSettingsService.java

License:Apache License

public static List<TicketCreationError> expireOldErrors(final PluginSettings pluginSettings) {
    logger.debug("Pulling error messages from settings");
    final Object errorObject = pluginSettings.get(HubJiraConstants.HUB_JIRA_ERROR);
    if (errorObject == null) {
        logger.debug("No error messages found in settings");
        return null;
    }/*from  w w  w .j a v  a  2 s .  c  o m*/
    if (!(errorObject instanceof String)) {
        logger.warn(
                "The error object in settings is invalid (probably stored by an older version of the plugin); discarding it");
        pluginSettings.remove(HubJiraConstants.HUB_JIRA_ERROR);
        return null;
    }

    List<TicketCreationError> ticketErrors = null;
    final String ticketErrorsString = (String) errorObject;
    try {
        ticketErrors = TicketCreationError.fromJson(ticketErrorsString);
    } catch (final Exception e) {
        logger.warn("Error deserializing JSON string pulled from settings: " + e.getMessage()
                + "; resettting error message list");
        pluginSettings.remove(HubJiraConstants.HUB_JIRA_ERROR);
        return null;
    }
    if ((ticketErrors == null) || ticketErrors.isEmpty()) {
        logger.debug("No error messages found in settings");
        return null;
    }
    logger.debug("# error messages pulled from settings: " + ticketErrors.size());
    Collections.sort(ticketErrors);
    final DateTime currentTime = DateTime.now();
    final Iterator<TicketCreationError> expirationIterator = ticketErrors.iterator();
    while (expirationIterator.hasNext()) {
        final TicketCreationError ticketError = expirationIterator.next();
        final DateTime errorTime = ticketError.getTimeStampDateTime();
        if (Days.daysBetween(errorTime, currentTime).isGreaterThan(Days.days(30))) {
            logger.debug("Removing old error message with timestamp: " + ticketError.getTimeStamp());
            expirationIterator.remove();
        }
    }
    logger.debug("Saving " + ticketErrors.size() + " non-expired error messages in settings");
    pluginSettings.put(HubJiraConstants.HUB_JIRA_ERROR, TicketCreationError.toJson(ticketErrors));
    return ticketErrors;
}

From source file:com.ceutecsps.adminplanilla.beans.ActividadesBean.java

public void generarNuevaActividad() {
    try {/*  ww w . j  a v a 2  s.  com*/
        mapShowSelectedLabor = new HashMap();
        listaActividades = new ArrayList();
        if (Days.daysBetween(new DateTime(fromDate), new DateTime(toDate)).getDays() == 4) {
            generarListaFechas(fromDate, toDate);
            renderizarTablaActividad = true;
        } else {
            renderizarTablaActividad = false;
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Error!", "Por favor escoger 1 semana solamente (5 dias)"));
        }
    } catch (Exception ex) {
        Logger.getLogger(ActividadesBean.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.ceutecsps.adminplanilla.beans.PlanillasBean.java

public void crearPlanilla() {
    if (Days.daysBetween(new DateTime(fromDate), new DateTime(toDate)).getDays() == 4) {
        if (planDAO.findBetweenDates(new java.sql.Date(fromDate.getTime()),
                new java.sql.Date(toDate.getTime()))) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Error! Ya existe una planilla para esos dias", null));
            return;
        }// w  w  w.  j  a va 2  s.  c om
        renderizarTablaActividad = true;
        listaActividades = actDAO.findActividadExistente(fromDate, toDate);
    } else {
        renderizarTablaActividad = false;
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Error! Por favor escoger 1 semana para crear planilla", null));
    }
}

From source file:com.chiorichan.http.ssl.CertificateWrapper.java

License:Mozilla Public License

/**
 * Returns the number of days left on this certificate
 * Will return -1 if already expired//from w w  w.j av a  2s  .co  m
 */
public int daysRemaining() {
    if (isExpired())
        return -1;
    return Days.daysBetween(LocalDate.fromDateFields(new Date()), LocalDate.fromDateFields(cert.getNotAfter()))
            .getDays();
}

From source file:com.cinco.InvoiceData.java

/**
 * Adds a particular equipment (corresponding to <code>productCode</code> to an 
 * invoice corresponding to the provided <code>invoiceCode</code> with the given
 * begin/end dates//from  w  w  w  .j  a v a 2 s  . c o  m
 */
public static void addLicenseToInvoice(String invoiceCode, String productCode, String startDate,
        String endDate) {
    Connection conn = null;
    PreparedStatement ps = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(DataInfo.url, DataInfo.username, DataInfo.password);
        String equipmentInvoiceQuery = "INSERT INTO InvoiceProducts (InvoiceCode, ProductCode, Quantity) VALUES (?, ?, ?);";
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date start = null;
        try {
            start = df.parse(startDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date end = null;
        try {
            end = df.parse(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        double quantity = (Days.daysBetween(new LocalDate(start), new LocalDate(end)).getDays());
        ps = conn.prepareStatement(equipmentInvoiceQuery);
        ps.setString(1, invoiceCode);
        ps.setString(2, productCode);
        ps.setDouble(3, quantity);
        ps.executeUpdate();
        //            String updateQuery = "UPDATE InvoiceProducts, Products SET InvoiceProducts.ProductID = Products.ProductID WHERE InvoiceProducts.ProductCode = Products.ProductCode;";
        //            ps.executeUpdate(updateQuery);
        //            updateQuery = "UPDATE InvoiceProducts, Invoices SET InvoiceProducts.InvoiceID = Invoices.InvoiceID WHERE InvoiceProducts.InvoiceCode = Invoices.InvoiceCode;";
        //            ps.executeUpdate(updateQuery);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            se.printStackTrace();
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.cisco.dvbu.ps.utils.date.DateDiffDate.java

License:Open Source License

/**
 * Called to invoke the stored procedure.  Will only be called a
 * single time per instance.  Can throw CustomProcedureException or
 * SQLException if there is an error during invoke.
 *///  www .java 2  s .c  o  m
public void invoke(Object[] inputValues) throws CustomProcedureException, SQLException {
    java.util.Date startDate = null;
    java.util.Date endDate = null;
    Calendar startCal = null;
    Calendar endCal = null;
    DateTime startDateTime = null;
    DateTime endDateTime = null;
    String datePart = null;
    long dateLength = 0;

    try {
        result = null;
        if (inputValues[0] == null) {
            result = new Long(dateLength);
            return;
        }

        if (inputValues[1] == null) {
            result = new Long(dateLength);
            return;
        }

        if (inputValues[2] == null) {
            result = new Long(dateLength);
            return;
        }

        datePart = (String) inputValues[0];
        startDate = (java.util.Date) inputValues[1];
        startCal = Calendar.getInstance();
        startCal.setTime(startDate);

        endDate = (java.util.Date) inputValues[2];
        endCal = Calendar.getInstance();
        endCal.setTime(endDate);

        startDateTime = new DateTime(startCal.get(Calendar.YEAR), startCal.get(Calendar.MONTH) + 1,
                startCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0, 0);
        endDateTime = new DateTime(endCal.get(Calendar.YEAR), endCal.get(Calendar.MONTH) + 1,
                endCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0, 0);

        if (datePart.equalsIgnoreCase("second")) {
            Seconds seconds = Seconds.secondsBetween(startDateTime, endDateTime);
            dateLength = seconds.getSeconds();
        }

        if (datePart.equalsIgnoreCase("minute")) {
            Minutes minutes = Minutes.minutesBetween(startDateTime, endDateTime);
            dateLength = minutes.getMinutes();
        }

        if (datePart.equalsIgnoreCase("hour")) {
            Hours hours = Hours.hoursBetween(startDateTime, endDateTime);
            dateLength = hours.getHours();
        }

        if (datePart.equalsIgnoreCase("day")) {
            Days days = Days.daysBetween(startDateTime, endDateTime);
            dateLength = days.getDays();
        }

        if (datePart.equalsIgnoreCase("week")) {
            Weeks weeks = Weeks.weeksBetween(startDateTime, endDateTime);
            dateLength = weeks.getWeeks();
        }

        if (datePart.equalsIgnoreCase("month")) {
            Months months = Months.monthsBetween(startDateTime, endDateTime);
            dateLength = months.getMonths();
        }

        if (datePart.equalsIgnoreCase("year")) {
            Years years = Years.yearsBetween(startDateTime, endDateTime);
            dateLength = years.getYears();
        }

        result = new Long(dateLength);
    } catch (Throwable t) {
        throw new CustomProcedureException(t);
    }
}

From source file:com.codenvy.api.license.SystemLicense.java

License:Open Source License

/**
 * Returns:/*from w ww .j ava 2 s.com*/
 * 1) days between current date and expiration date + additional time to renew it;
 * 2) 0 if time for license renew expired;
 * 3) -1 if license isn't expired.
 */
public int daysBeforeTimeForRenewExpires() {
    if (isTimeForRenewExpired()) {
        return 0;
    }

    if (!isExpired()) {
        return -1;
    }

    int wholeDaysBeforeLicenseRenewExpires = Days
            .daysBetween(new DateTime(getCurrentTime()), new DateTime(getLicenseRenewExpirationDate()))
            .getDays();
    return wholeDaysBeforeLicenseRenewExpires + 1;
}

From source file:com.divudi.bean.pharmacy.ReportsTransfer.java

public void fillMovingWithStock() {
    String sql;// w  w  w.ja  va 2 s. com
    Map m = new HashMap();
    m.put("i", institution);
    m.put("t1", BillType.PharmacyTransferIssue);
    m.put("t2", BillType.PharmacyPre);
    m.put("fd", fromDate);
    m.put("td", toDate);
    BillItem bi = new BillItem();

    sql = "select bi.item, abs(SUM(bi.pharmaceuticalBillItem.qty)), "
            + "abs(SUM(bi.pharmaceuticalBillItem.stock.itemBatch.purcahseRate * bi.pharmaceuticalBillItem.qty)), "
            + "SUM(bi.pharmaceuticalBillItem.stock.itemBatch.retailsaleRate * bi.qty)) "
            + "FROM BillItem bi where bi.retired=false and  bi.bill.department.institution=:i and "
            + "(bi.bill.billType=:t1 or bi.bill.billType=:t2) and "
            + "bi.bill.billDate between :fd and :td group by bi.item "
            + "order by  SUM(bi.pharmaceuticalBillItem.qty) desc";
    List<Object[]> objs = getBillItemFacade().findAggregates(sql, m);
    movementRecordsQty = new ArrayList<>();
    for (Object[] obj : objs) {
        StockReportRecord r = new StockReportRecord();
        r.setItem((Item) obj[0]);
        r.setQty((Double) obj[1]);
        Days daysBetween = Days.daysBetween(LocalDate.fromDateFields(fromDate),
                LocalDate.fromDateFields(toDate));
        int ds = daysBetween.getDays();
        r.setPurchaseValue((Double) (r.getQty() / ds));
        //            r.setRetailsaleValue((Double) obj[2]);
        r.setStockQty(getPharmacyBean().getStockQty(r.getItem(), institution));
        movementRecordsQty.add(r);
    }
}

From source file:com.divudi.bean.store.StoreReportsTransfer.java

public void fillMovingWithStock() {
    String sql;//ww w .ja  v a2 s  .com
    Map m = new HashMap();
    m.put("i", institution);
    m.put("t1", BillType.StoreTransferIssue);
    m.put("t2", BillType.StorePre);
    m.put("fd", fromDate);
    m.put("td", toDate);
    BillItem bi = new BillItem();

    sql = "select bi.item, abs(SUM(bi.pharmaceuticalBillItem.qty)), "
            + "abs(SUM(bi.pharmaceuticalBillItem.stock.itemBatch.purcahseRate * bi.pharmaceuticalBillItem.qty)), "
            + "SUM(bi.pharmaceuticalBillItem.stock.itemBatch.retailsaleRate * bi.qty)) "
            + "FROM BillItem bi where bi.retired=false and  bi.bill.department.institution=:i and "
            + "(bi.bill.billType=:t1 or bi.bill.billType=:t2) and "
            + "bi.bill.billDate between :fd and :td group by bi.item "
            + "order by  SUM(bi.pharmaceuticalBillItem.qty) desc";
    List<Object[]> objs = getBillItemFacade().findAggregates(sql, m);
    movementRecordsQty = new ArrayList<>();
    for (Object[] obj : objs) {
        StockReportRecord r = new StockReportRecord();
        r.setItem((Item) obj[0]);
        r.setQty((Double) obj[1]);
        Days daysBetween = Days.daysBetween(LocalDate.fromDateFields(fromDate),
                LocalDate.fromDateFields(toDate));
        int ds = daysBetween.getDays();
        r.setPurchaseValue((Double) (r.getQty() / ds));
        //            r.setRetailsaleValue((Double) obj[2]);
        r.setStockQty(getStoreBean().getStockQty(r.getItem(), institution));
        movementRecordsQty.add(r);
    }
}

From source file:com.dnsoft.inmobiliaria.utils.CalculaMora.java

public boolean verificaSiAplicaMora() {

    // int tolerancia = alquier.getContrato().getToleranciaMora();
    Date vencimiento = alquier.getFechaVencimiento();

    DateTime vencimientoCalendar = new DateTime(vencimiento);
    DateTime fechaPago = new DateTime(new Date());

    int diasVencidos = Days.daysBetween(vencimientoCalendar, fechaPago).getDays();

    return 1 > diasVencidos;

}