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.zappy.purefit6.service.UserHistoricFacadeREST.java

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void create(@FormDataParam("breakfast") Boolean hadBreakfast,
        @FormDataParam("totalFruits") Integer fruits, @FormDataParam("totalSteps") Integer steps,
        @FormDataParam("weight") Float weight, @FormDataParam("idDay") Integer idDay,
        @FormDataParam("idUser") Integer idUser) {

    User user = null;/* w  w w .j  av  a 2s .  com*/
    UserHistoric previous = null;
    int index = 0;

    user = (User) em.createNamedQuery("User.findByIdUser").setParameter("idUser", idUser).getSingleResult();

    try {
        previous = (UserHistoric) em.createNamedQuery("UserHistoric.findFirstByIdUser")
                .setParameter("idUser", user).setMaxResults(1).getSingleResult();
        log.info("todays: " + new DateTime() + " previous " + new DateTime(previous.getSubmitted()));
        int days = Days.daysBetween(new DateTime(previous.getSubmitted()), new DateTime()).getDays();
        log.info("total days between: " + days);
        index = days + 1;
    } catch (NoResultException ex) {
        index++;
    }

    UserHistoric historic = new UserHistoric();
    historic.setBreakfast(hadBreakfast);
    historic.setIdDay(index);
    historic.setSteps(steps);
    historic.setSubmitted(new Date());
    historic.setTotalFruits(fruits);
    historic.setWeight(weight);
    historic.setIdUser(user);
    super.create(historic);
}

From source file:common.CommonFunction.java

public static int calculateDayBetweenTwoDate(Date date1, Date date2) {
    return Days.daysBetween(new DateTime(date1), new DateTime(date2)).getDays();
}

From source file:control.EmprestimoController.java

public static boolean Renovar(int id, int plus_days) {
    dao = new EmprestimoDAO();
    Emprestimo e = dao.get(id);//  ww  w  .j  a va 2  s .co  m
    if (e != null) {
        LocalDateTime hoje = new LocalDateTime(System.currentTimeMillis());
        LocalDateTime fim = new LocalDateTime(e.getData_fim());
        int dias = Days.daysBetween(hoje, fim).getDays();
        dias = dias * -1;
        if (dias > 0)
            e.setData_fim(hoje.plusDays(plus_days));
        else
            e.setData_fim(fim.plusDays(plus_days));
        dao = new EmprestimoDAO();
        return dao.update(e);
    }
    return false;
}

From source file:Controlador.PrestamoController.java

private boolean validarCliente(Cliente cliente) {

    ArrayList<Prestamo> prestamoL = prestamoArray;
    Iterator it = prestamoL.iterator();
    Date now = new Date();
    HashMap<String, Object> conf = Config.getInstance().getPrestamoCliente();
    String tipo = cliente.getClass().toString();

    HashMap<String, Object> confCliente = (HashMap<String, Object>) conf.get(tipo);

    int dias = (int) confCliente.get("dias");
    int libro = (int) confCliente.get("libros");
    int cont = 0;
    while (it.hasNext()) //mientras queden elementos
    {// w  w  w.  j  av  a 2s.  co m
        Prestamo pres = (Prestamo) it.next();
        if (cliente.equals(pres.getCliente())) {
            if ("0".equals(pres.getFechaDevolucion())) {
                Date fecha = new Date(pres.getFecha());
                int days = Days.daysBetween(new DateTime(fecha), new DateTime(now)).getDays();
                System.out.println(pres.getFechaDevolucion() + "--" + dias + "--" + days);
                cont++;
                if (dias > days) {
                    return false;
                }
            }
        }
    }

    return true;
}

From source file:controllers.chqbll.Partials.java

License:Open Source License

/**
 * Kayit isleminden once form uzerinde bulunan verilerin uygunlugunu kontrol eder
 * //from www.  j  ava2  s.c  o  m
 * @param filledForm
 */
private static void checkConstraints(Form<ChqbllPartialList> filledForm) {
    ChqbllPartialList model = filledForm.get();

    if (model.paid.doubleValue() < 1) {
        filledForm.reject("payment", Messages.get("error.min.strict", 0));
    }

    if (model.remaining.doubleValue() < 0) {
        filledForm.reject("remain", Messages.get("error.min", 0));
    }

    List<ValidationError> veList = new ArrayList<ValidationError>();
    if (model.details != null && model.details.size() > 0) {

        ChqbllPayrollDetail detail = ChqbllPayrollDetail.findById(model.detailId);
        DateTime dueDate = new DateTime(detail.dueDate);

        for (int i = 1; i < model.details.size() + 1; i++) {
            ChqbllDetailPartial std = model.details.get(i - 1);

            if (std.amount == null || std.amount <= 0) {
                veList.add(new ValidationError("partials", Messages.get("cannot.be.zero.table", i)));
            }
            if (std.transDate == null) {
                veList.add(new ValidationError("partials",
                        Messages.get("is.not.null.for.table", i, Messages.get("date.maturity"))));
            } else {
                DateTime transDate = new DateTime(std.transDate);
                Days days = Days.daysBetween(dueDate, transDate);

                if (days.getDays() < 0) {
                    veList.add(
                            new ValidationError("partials", Messages.get("date.less.from.due.for.table", i)));
                }
            }
        }

    } else {
        veList.add(new ValidationError("partials", Messages.get("table.min.row.alert")));
    }

    if (veList.size() > 0) {
        filledForm.errors().put("partials", veList);
    }
}

From source file:controllers.chqbll.Payrolls.java

License:Open Source License

private static void checkSecondConstraints(Form<ChqbllPayroll> filledForm) {
    ChqbllPayroll model = filledForm.get();

    List<ValidationError> veList = new ArrayList<ValidationError>();

    if (model.details != null && model.details.size() > 0) {

        DateTime transDate = new DateTime(model.transDate);
        for (int i = 1; i < model.details.size() + 1; i++) {
            ChqbllPayrollDetail std = model.details.get(i - 1);

            if (std.amount == null || std.amount <= 0) {
                veList.add(new ValidationError("chqblls", Messages.get("cannot.be.zero.table", i)));
            }//from   w  w w .j  av  a2s . com
            if (std.dueDate == null) {
                veList.add(new ValidationError("chqblls",
                        Messages.get("is.not.null.for.table", i, Messages.get("date.maturity"))));
            } else if (isNormalPayroll(model.right)) {
                DateTime dueDate = new DateTime(std.dueDate);
                Days days = Days.daysBetween(transDate, dueDate);

                if (days.getDays() < 1) {
                    veList.add(new ValidationError("chqblls", Messages.get("duedate.close.for.table", i)));
                }
            }
        }

    } else {
        veList.add(new ValidationError("chqblls", Messages.get("table.min.row.alert")));
    }

    if (veList.size() > 0) {
        filledForm.errors().put("chqblls", veList);
    }
}

From source file:controllers.chqbll.Trans.java

License:Open Source License

private static void checkSecondConstraints(Form<ChqbllTrans> filledForm) {
    ChqbllTrans model = filledForm.get();

    Module refModule = ChqbllStep.findRefModule(model.fromStep, model.toStep);
    switch (refModule) {
    case safe: {//from   www  .  j  a v a  2s  .  co  m
        model.bank = null;
        model.contact = null;
        if (model.safe.id == null) {
            filledForm.reject("safe.name", Messages.get("is.not.null", Messages.get("safe")));
        }
        break;
    }
    case bank: {
        model.safe = null;
        model.contact = null;
        if (model.bank.id == null) {
            filledForm.reject("bank.name", Messages.get("is.not.null", Messages.get("bank")));
        }
        break;
    }
    case contact: {
        model.safe = null;
        model.bank = null;
        if (model.contact.id == null) {
            filledForm.reject("contact.name", Messages.get("is.not.null", Messages.get("contact")));
        }
        break;
    }

    default: {
        model.bank = null;
        model.safe = null;
        model.contact = null;
    }
    }

    List<ValidationError> veList = new ArrayList<ValidationError>();
    if (model.virtuals != null && model.virtuals.size() < 1) {
        veList.add(new ValidationError("chqblls", Messages.get("table.min.row.alert")));
    } else {
        DateTime transDate = new DateTime(model.transDate);
        for (int i = 1; i < model.virtuals.size() + 1; i++) {
            ChqbllPayrollDetail std = model.virtuals.get(i - 1);
            if (ChqbllStep.Endorsed.equals(model.toStep)) {
                ChqbllPayrollDetail detail = ChqbllPayrollDetail.findById(std.id);
                if (detail.contact.equals(model.contact)) {
                    veList.add(new ValidationError("chqblls", Messages.get("contacts.are.same.table", i)));
                }
            }

            DateTime dueDate = new DateTime(std.dueDate);
            Days days = Days.daysBetween(transDate, dueDate);

            if (days.getDays() < 1) {
                veList.add(new ValidationError("chqblls", Messages.get("duedate.close.for.table", i)));
            }
        }
    }

    if (veList.size() > 0) {
        filledForm.errors().put("chqblls", veList);
    }
}

From source file:controllers.Deputados.java

License:Open Source License

/**
 * Dados de 2012 e 2013/*www .j  av a2s .  c  o  m*/
 * @return
 */
@Transactional
public static void getTotalsData() {

    System.out.println("Processando totais dos Deputados...");

    //Pega o ltimo dia com registro
    String mostRecent = (String) JPA.em()
            .createNativeQuery("Select max(datEmissao) FROM DeputadoFederalGasto WHERE datEmissao < NOW()")
            .getSingleResult();
    Date mostRecentDate = null;
    Date olderDate = null;

    try {
        mostRecentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(mostRecent);
        olderDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2013-01-01");
    } catch (ParseException e) {
        System.out.println("Error getting mostRecentDate. " + e.getLocalizedMessage());
    }

    List<DeputadoFederal> depList = JPA.em().createQuery("FROM DeputadoFederal").getResultList();

    /**
     * Salva o gasto medio por dia
     */

    for (DeputadoFederal dep : depList) {
        System.out.println("Calculando gasto de " + dep.getNomeParlamentar());
        int days = 0;
        Date dataIni, dataFim;

        /** TODO Repensar e refazer essa conta do exerccio DIREITO */
        /* List<DeputadoFederalExercicio> exeList =
              JPA.em().createQuery(" FROM DeputadoFederalExercicio e where e.ideCadastro = :id")
              .setParameter("id", dep.getIdeCadastro())
              .getResultList();
                
        for (DeputadoFederalExercicio exe: exeList){
           dataFim = exe.getDataFim();
           dataIni = exe.getDataInicio();
                   
           if (dataFim == null) dataFim = mostRecentDate;
           if (dataFim.getTime() < olderDate.getTime()) continue;
                   
           if (dataIni.getTime() < olderDate.getTime()) dataIni = olderDate;
           if (dataIni.getTime() > mostRecentDate.getTime()) continue;
                   
           days += Days.daysBetween(new DateTime(dataIni), new DateTime(dataFim)).getDays();
                   
        }*/

        days = Days.daysBetween(new DateTime(olderDate), new DateTime(mostRecentDate)).getDays();
        dep.setDiasTrabalhados(days);

        /////////////////////////
        Object o = JPA.em().createNativeQuery(
                "select sum(vlrDocumento) as TotalGasto from DeputadoFederalGasto g where g.nuCarteiraParlamentar = :id")
                .setParameter("id", dep.getMatricula()).getSingleResult();

        if (o != null) {
            Double gasto = (Double) o;
            dep.setGastoTotal(gasto);

            dep.setGastoPorDia(gasto / days);
        }
        JPA.em().persist(dep);
    }

    JPA.em().getTransaction().commit();
    JPA.em().getTransaction().begin();

    /**
     * Calcula o ndice do candidato:
     * 100*gasto/max
     * Ou seja: o candidato que gastou MAIS tem valor 100, o candidato que gastou NADA tem valor 0 
     */

    Double maxGasto = (Double) JPA.em().createNativeQuery("Select max(gastoPorDia) FROM DeputadoFederal")
            .getSingleResult();
    Double gasto, depTempIndice;

    for (DeputadoFederal dep : depList) {
        gasto = dep.getGastoPorDia();

        depTempIndice = (100 * gasto / maxGasto);

        dep.setIndice(depTempIndice.intValue());

        JPA.em().persist(dep);
    }

    System.out.println("Sucesso processando totais dos Deputados!");
}

From source file:controllers.Senadores.java

License:Open Source License

/**
 * Dados de 2010 at a ltima data disponvel
 * TODO: Calcular os dias corretamente, com os afastamentos
 * @throws Exception /*w  ww.  j av  a2 s .  c  o m*/
 */
@Transactional
private static void getTotalsData() throws Exception {

    System.out.println("Processando totais dos Senadores...");

    //Pega o ltimo dia com registro
    Date mostRecentDate = (Date) JPA.em()
            .createNativeQuery("Select max(data) FROM SenadorGasto WHERE data < NOW()").getSingleResult();

    Date olderDate;

    try {
        olderDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2010-01-01");
    } catch (ParseException e) {
        throw new Exception("Error getting mostRecentDate. " + e.getLocalizedMessage());
    }

    int days = Days.daysBetween(new DateTime(olderDate), new DateTime(mostRecentDate)).getDays();

    List<Senador> senadores = JPA.em().createQuery("FROM Senador").getResultList();

    Double gasto;
    for (Senador senador : senadores) {
        senador.setDiasTrabalhados(days);

        Object o = JPA.em()
                .createNativeQuery("select sum(valor_reembolsado) from SenadorGasto where senador = :nome")
                .setParameter("nome", senador.getNomeParlamentar()).getSingleResult();

        if (o != null) {
            gasto = (Double) o;
            senador.setGastoTotal(gasto);

            senador.setGastoPorDia(gasto / days);
        }
        JPA.em().persist(senador);
    }

    JPA.em().getTransaction().commit();
    JPA.em().getTransaction().begin();

    /**
     * Calcula o ndice do candidato
     * 100*gasto/max
     * Ou seja: o candidato que gastou MAIS tem valor 0, o candidato que gastou NADA tem valor 100 
     */

    Double maxGasto = (Double) JPA.em().createNativeQuery("Select max(gastoPorDia) FROM Senador")
            .getSingleResult();
    Double senTempIndice;

    for (Senador sen : senadores) {
        gasto = sen.getGastoPorDia();

        senTempIndice = (100 * gasto / maxGasto);

        sen.setIndice(senTempIndice.intValue());

        JPA.em().persist(sen);
    }
    System.out.println("Sucesso processando totais dos Senadores!");
}

From source file:courtscheduler.domain.DateConstraint.java

License:Apache License

public Integer findDate(LocalDate date) {
    //System.out.println(Days.daysBetween(info.getStartingDay(), Date).getDays());
    int day = Days.daysBetween(info.getConferenceStartDate(), date).getDays();
    int conferenceLength = info.getNumberOfConferenceDays();
    if (day < 0) {
        warning("date \"" + date + "\" is before conference start." + "\tFound in " + currentCell());
        return null;
    }//from w ww  .j  av a2  s  .com
    if (day > conferenceLength) {
        warning("date \"" + date + "\" is after conference start." + "\tFound in " + currentCell());
        return null;
    }
    return day;
}