Problem data Date in method jsf

1

It may be a silly question but I have not been able to solve the problem I have the following methods:

public long contarPedidosMeses(int cedulaCliente, int codigoProducto, Date fechaIni, Date fechaFin){

    Query q;
    q = em.createNativeQuery("SELECT COUNT(*) FROM pedidos, pedidoproducto WHERE fechaDeSolicitud BETWEEN ? AND ? and pedidos.cedulaCliente=? and pedidoproducto.codigoProducto=? and pedidos.idPedido= pedidoproducto.idPedido");
    q.setParameter(1,fechaIni);
    q.setParameter(2, fechaFin);
    q.setParameter(3, cedulaCliente);
    q.setParameter(4, codigoProducto);
    long valor=Long.parseLong(q.getSingleResult().toString());
    return valor;
}


public long valoresMeses(Date fechaI, Date fechaF, int cedula, int codigo){

    long valores= productosf.contarPedidosMeses(cedula, codigo, fechaI, fechaF);
    return valores;
}

The problem I have is that I do not know how to pass the Date data when calling the method. Therefore, the query does not work for me.

I have treated it in the following way:

controladorProducto.valoresMeses('2016/01/01', '2016/01/31', controladorUsuario.objUsuarioLogin.idUsuario, 1)

Also changing the place of the numbers ie (dd / mm / yyyy), but it does not work either. In the method valuesMeses () I have changed that I do not receive a Date but a String and I try to convert it with SimpleDateFormat but it sends me a very different date when I convert it. I do not know what else I would really appreciate your help.

I work on jsf, JPA and the MySQL database.

    
asked by Lina Cortés 29.05.2016 в 19:43
source

1 answer

1

Your parameters must be of type Date . If you want to build Date objects from a text string (for your tests maybe), I recommend using SimpleDateFormat :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date fechaI = sdf.parse("2016/01/01");
Date fechaF = sdf.parse("2016/01/31");
int cedula = ...;
int codigo = ...;
valoresMeses(fechaI, fechaF, cedula, codigo);

You can save work by creating utilitarian methods:

//diseño básico, puede ser mejorado
public class MiDateUtils {
    public static Date parseaFecha(String fecha) {
        return parseaFecha(fecha, "yyyy/MM/dd");
    }
    //en caso que necesites utilizar otro formato como dd-MM-yyyy o dd/MM/yyyy o MM/dd/yyyy u otro
    public static Date parseaFecha(String fecha, String formato) {
        Date resultado = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(formato);
            resultado = sdf.format(fecha);
        } catch (Exception e) {
            //maneja la excepción, mandalo a un log o algo
        }
        return resultado;
    }
}

Thus the previous code is reduced to:

Date fechaI = MiDateUtils.parseaFecha("2016/01/01");
Date fechaF = MiDateUtils.parseaFecha("2016/01/31");
int cedula = ...;
int codigo = ...;
valoresMeses(fechaI, fechaF, cedula, codigo);
    
answered by 29.05.2016 / 23:41
source