Foros del Web » Programación para mayores de 30 ;) » Java »

problemas con fechas en parametros en jasperreport

Estas en el tema de problemas con fechas en parametros en jasperreport en el foro de Java en Foros del Web. Hola, tengo un problema al pasar unas fechas como parámetros a un jasperreport, si utilizo la query select * from arrivalFlight a, departureFlight b where ...
  #1 (permalink)  
Antiguo 21/07/2011, 01:43
 
Fecha de Ingreso: diciembre-2008
Mensajes: 233
Antigüedad: 15 años, 4 meses
Puntos: 1
problemas con fechas en parametros en jasperreport

Hola, tengo un problema al pasar unas fechas como parámetros a un jasperreport, si utilizo la query

select * from arrivalFlight a, departureFlight b where a.scheduledTime between '2011-06-09 10:11:00' and '2011-06-09 10:11:00' and b.scheduledTime between '2011-06-09 10:11:00' and '2011-06-09 10:11:00' order by a.scheduledTime,b.scheduledTime

estupendo, pero si le paso las fechas como parámetros:

select * from arrivalFlight a, departureFlight b where a.scheduledTime between $P{fechaInformeDesde} and $P{fechaInformeHasta} and b.scheduledTime between $P{fechaInformeDesde} and $P{fechaInformeHasta} order by a.scheduledTime,b.scheduledTime

no me devuelve nada. He visto en este mismo foro un antiguo tema:

Cita:
Respuesta: Formato de fechas en ireport como parametros

--------------------------------------------------------------------------------
SELECCIONÁ el parámetro(textField) EN/DENTRO de la hoja del Reporte, no en el Report Inspector (a la izquierda)
Google suele ser una buena herramienta
http://www.google.com.ar/search?clie...utf-8&oe=utf-8

----------------------------------------------------------------------------------------------
We will modify the elements of Page Footer now. To change the date format, select date element (new java.util.Date()), go to Properties | Text Field Properties, and see the Pattern.

http://www.packtpub.com/sites/defaul...8808_03_19.png


Now, follow the steps listed to change the date pattern:
Open the pattern editor by clicking the button next to Pattern.
Select Date from Category.
Select dd/MM/yyyy h.mm a from the Type window.
http://www.packtpub.com/sites/defaul...8808_03_20.png

Press OK. The date pattern is changed to the output, as shown in the following screenshot:
pero yo no tengo el parámetro dentro de la hoja de reporte, sólamente en la consulta, por lo que no encuentro en properties el "pattern".

Podría alguien darme una idea de cual es mi error? Igual el formato que le paso no es el adecuado.

Un saludo
  #2 (permalink)  
Antiguo 21/07/2011, 05:58
 
Fecha de Ingreso: junio-2011
Mensajes: 39
Antigüedad: 12 años, 10 meses
Puntos: 16
Respuesta: problemas con fechas en parametros en jasperreport

Hola,

Estas seguro que las estas enviando como Strings y en el mismo formato del query que te funciona?,,las variables $P{fecha.... deben estar creados como String en el reporte,

busca en google to_date (oracle) o format(SQL Server) para trabajar con fechas en consultas.

espero sea de ayuda
__________________
Saludos desde Colombia.
http://labs.distrit.co
  #3 (permalink)  
Antiguo 21/07/2011, 07:48
 
Fecha de Ingreso: diciembre-2008
Mensajes: 233
Antigüedad: 15 años, 4 meses
Puntos: 1
Respuesta: problemas con fechas en parametros en jasperreport

Hola, lo primero muchas gracias por responder. He estado revisando la query y creo que no está bien hecha, la sigo revisando para obtener lo que busco. Por ahora va como sigue:

Cita:
select a.iataCompanyCode as company, a.flightNumber as flightNumber,a.scheduledTime as scheduledTime, a.statusCode as statusCode, a.flightTypeCode as tipoVuelo from `aodb`.`arrivalFlight` a where a.scheduledTime between '2011-07-20 00:00:00' and '2011-07-20 23:59:59' union all (select b.iataCompanyCode as company, b.flightNumber as idDeparture,b.scheduledTime as scheduledTime, b.statusCode as statusCode, b.flightTypeCode as tipoVuelo from `aodb`.`departureFlight` b where b.scheduledTime between '2011-05-07 00:00:00' and '2011-05-07 23:59:59') order by scheduledTime;
estoy buscando la manera de hacer que al hacer la consulta, me cree un campo nuevo, y lo rellene con el valor de un campo de una tercera tabla distinta de las dos principales de dónde obtengo los datos, y que está relacionada con ellas por el id. Es decir, que tengo la consulta a las dos tablas arrivalFlight y departureFlight, y luego necesito el valor de unos campos de una tercera tabla tabla3, relacionada con las otras dos por un campo común. Luego sólo sería sustituir las fechas por parámetros en el jasperreport. Cuando lo tenga todo y funcione correctamente lo pondré por si puede ayudar a alguien.

Un saludo
  #4 (permalink)  
Antiguo 22/07/2011, 03:20
 
Fecha de Ingreso: diciembre-2008
Mensajes: 233
Antigüedad: 15 años, 4 meses
Puntos: 1
Respuesta: problemas con fechas en parametros en jasperreport

Hola, por ahora sigo con el mismo problema de las fechas. Mi consulta es la siguiente:

Cita:
select a.iataCompanyCode as company, a.flightNumber as flightNumber, a.scheduledTime as scheduledTime, a.statusCode as statusCode, a.flightTypeCode as flightType, (select aa.SeatNumber from `aodb`.`aircraft` aa where aa.tailNumber = a.tailNumber) as seats, (select aaa.pax from `aodb`.`paxmerchandisepost` aaa where aaa.idArrivalFlight = a.idArrivalFlight) as passengers, if ((select aaa.pax from `aodb`.`paxmerchandisepost` aaa where aaa.idArrivalFlight = a.idArrivalFlight) is null and (select aa.SeatNumber from `aodb`.`aircraft` aa where aa.tailNumber = a.tailNumber and a.tailnumber is not null),0,(100 - ((select aa.SeatNumber from `aodb`.`aircraft` aa where aa.tailNumber = a.tailNumber)-(select aaa.pax from `aodb`.`paxmerchandisepost` aaa where aaa.idArrivalFlight = a.idArrivalFlight))/(select aa.SeatNumber from `aodb`.`aircraft` aa where aa.tailNumber = a.tailNumber) * 100)) as ocupation from `aodb`.`arrivalFlight` a where a.scheduledTime between '2011-07-20 00:00:00' and '2011-07-20 23:59:59' union all (select b.iataCompanyCode as company, b.flightNumber as idDeparture, b.scheduledTime as scheduledTime, b.statusCode as statusCode, b.flightTypeCode as flightType, (select bb.SeatNumber from `aodb`.`aircraft` bb where bb.tailNumber = b.tailNumber) as seats, (select bbb.pax from `aodb`.`paxmerchandisepost` bbb where bbb.idDepartureFlight = b.idDepartureFlight) as passengers, if ((select bbb.pax from `aodb`.`paxmerchandisepost` bbb where bbb.idDepartureFlight = b.idDepartureFlight) is null and (select bb.SeatNumber from `aodb`.`aircraft` bb where bb.tailNumber = b.tailNumber and b.tailnumber is not null),0,(100 - ((select bb.SeatNumber from `aodb`.`aircraft` bb where bb.tailNumber = b.tailNumber)-(select bbb.pax from `aodb`.`paxmerchandisepost` bbb where bbb.idDepartureFlight = b.idDepartureFlight))/(select bb.SeatNumber from `aodb`.`aircraft` bb where bb.tailNumber = b.tailNumber) * 100)) as ocupation from `aodb`.`departureFlight` b where b.scheduledTime between '2011-07-20 00:00:00' and '2011-07-20 23:59:59') order by scheduledTime;
que funciona perfectamente en la bbdd. La única diferencia es que en el jasperreport sustituyo :

between '2011-07-20 00:00:00' and '2011-07-20 23:59:59'

por

between $P{fechaInformeDesde} and $P{fechaInformeHasta}

En el jasperReport, tengo estos dos parámetros: fechaInformeDesde y fechaInformeHasta. A ambos, en sus properties, les he puesto:

en Parameter Class java.util.date
en Default value expression new java.util.Date()

En mi aplicación, relleno un campo con el valor: 20/07/2011, que va a un servlet que trae el jasperreport.
El código del servlet es el siguiente:

Código:
public class OperacionesDiariasYMensServlet extends HttpServlet
{
	private static final long serialVersionUID = 7154490521050615751L;
	
...	
		
		JasperPrint jasperPrint = null;
		JasperReport listadoDiarioOperacionesJasperReport = null;
		
		String tituloInforme = request.getParameter(TITULO_INFORME);
		String compania = request.getParameter(COMPANIA);
		String numeroVuelo = request.getParameter(NUMERO_VUELO);
		String fechaProgramada = request.getParameter(FECHA_PROGRAMADA);
		String estadoActual = request.getParameter(ESTADO_ACTUAL);
		String tipoVuelo = request.getParameter(TIPO_VUELO);
		String tipoAeronave = request.getParameter(TIPO_AERONAVE);
		String numeroAsientos = request.getParameter(NUMERO_ASIENTOS);
		String numeroPasajeros = request.getParameter(NUMERO_PASAJEROS);
		String ocupacion = request.getParameter(OCUPACION);
	
		HashMap parameters = new HashMap();
		parameters.put("tituloInforme", tituloInforme);
		parameters.put("compania", compania);
		parameters.put("numeroVuelo", numeroVuelo);
		parameters.put("fechaProgramada", fechaProgramada);
		parameters.put("estadoActual", estadoActual);
		parameters.put("tipoVuelo", tipoVuelo);
		parameters.put("tipoAeronave", tipoAeronave);
		parameters.put("numeroAsientos", numeroAsientos);
		parameters.put("numeroPasajeros", numeroPasajeros);
		parameters.put("ocupacion", ocupacion);
				
		SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
		SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String reportDateString = request.getParameter(REPORT_DATE_STRING);
		String reportMonth = request.getParameter(REPORT_MONTH);
		String reportYear = request.getParameter(REPORT_YEAR);
		//para el informe de operaciones diarias
		if (reportDateString != null && !reportDateString.equals(""))
		{
			try 
			{
				/*Date fechaInformeDesde = formatoFecha.parse(reportDateString + " 00:00:00");			
				Date fechaInformeHasta = formatoFecha.parse(reportDateString + " 23:59:59");*/
				String arrayFecha[] = reportDateString.split("/");	
				String dia = arrayFecha[0];
				String mes = arrayFecha[1];
				String anno = arrayFecha[2];
				reportDateString = anno + "-" + mes + "-" + dia;
				Date fechaInformeDesde = formato.parse(reportDateString + " 00:00:00");			
				Date fechaInformeHasta = formato.parse(reportDateString + " 23:59:59");
				
				//parameters.put("fechaInformeDesde", reportDateString + " 00:00:00");
				//parameters.put("fechaInformeHasta", reportDateString + " 23:59:59");
				parameters.put("fechaInformeDesde", fechaInformeDesde);
				parameters.put("fechaInformeHasta", fechaInformeHasta);
			} 
			catch (ParseException e) {
				logger.error("No se han transformado bien las fechas desde y hasta de informe, informe diario");
				errorsList.add("No se han transformado bien las fechas desde y hasta de informe, informe diario");
				e.printStackTrace();
			}
		}
		//para el informe de operaciones mensual
		else
		{
			try
			{
				int year = Integer.parseInt(reportYear);
				int month = Integer.parseInt(reportMonth);
				Date fechaInformeDesde = formatoFecha.parse("01/" + reportMonth + "/" + reportYear + " 00:00:00");
				GregorianCalendar calendario = new GregorianCalendar (year, month, 1);
				int numDays = calendario.getActualMaximum(Calendar.DAY_OF_MONTH);
				Date fechaInformeHasta = formatoFecha.parse(numDays + "/" + (month + 1) + "/" + reportYear + " 23:59:59");
				parameters.put("fechaInformeDesde", fechaInformeDesde);
				parameters.put("fechaInformeHasta", fechaInformeHasta);
			}
			catch (ParseException e1) {
				logger.error("No se han transformado bien las fechas desde y hasta de informe, informe mensual");
				errorsList.add("No se han transformado bien las fechas desde y hasta de informe, informe mensual");
				e1.printStackTrace();
			}
		}
		
		try 
		{
			listadoDiarioOperacionesJasperReport = (JasperReport) JRLoader.loadObject(this.getClass().getClassLoader().getResourceAsStream("es/indra/aodb/informes/web/action/informes/reportsJasper/ListadoOperacionesDiarias.jasper"));
			jasperPrint = JasperFillManager.fillReport(listadoDiarioOperacionesJasperReport, parameters, connection);
            if (jasperPrint != null) 
            {
                logger.debug("Se va a mostrar el informe");
                logger.debug("Informe mostrado");
                logger.debug("informe descargado");
                
                byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
                logger.debug("exportado a bytes");
                response.setContentType("application/pdf");
                response.setContentLength(bytes.length);
                response.setHeader( "Content-disposition", "inline; filename=reporte.pdf");
                ServletOutputStream ouputStream = response.getOutputStream();
                logger.debug("creada la salida ourputStream");
                ouputStream.write(bytes, 0, bytes.length);
                ouputStream.flush();
                ouputStream.close();
                
            } 
            else 
            {
                logger.error("No se ha generado el informe correctamente");
                errorsList.add("No se ha generado el informe correctamente");
            }
		} 
		catch (JRException e2) 
		{
			logger.debug(e2);
			errorsList.add(e2.getMessage());
			e2.printStackTrace();
		}
	}


	public Collection<String> getErrorsList() {
		return errorsList;
	}

	public void setErrorsList(Collection<String> errorsList) {
		this.errorsList = errorsList;
	}
y en los valores de fechaInformeDesde y fechaInformeHasta, he intentado meter las fechas, de tipo date, con formato "yyyy-MM-dd hh:mm:ss", que es como las veo en la bbdd.
No sé qué puedo estar haciendo mal. No veo ningún error en la consola.

¿Alguien me puede decir dónde puede estar el fallo?

Muchas gracias, un saludo

PD He quitado parte del código del servlet que no importaba demasiado porque me pasaba de caracteres
  #5 (permalink)  
Antiguo 22/07/2011, 06:25
 
Fecha de Ingreso: diciembre-2008
Mensajes: 233
Antigüedad: 15 años, 4 meses
Puntos: 1
Respuesta: problemas con fechas en parametros en jasperreport

Hola, ya lo tengo resuelto. El problema era que jasperreport me cogía la fecha con formato MM/dd/yyyy, y yo se lo pasaba de otra manera. Así que en la consulta he cambiado los:

a.scheduledTime between $P{fechaInformeDesde} and $P{fechaInformeHasta}

por

a. scheduledTime >= $P{fechaInformeDesde} and a. scheduledTime < $P{fechaInformeHasta}

y

b. scheduledTime >= $P{fechaInformeDesde} and b. scheduledTime < $P{fechaInformeHasta}

, y en el servlet, he hecho lo siguiente para conseguir el formato adecuado:

Código:
//obtengo el dia, mes y año introducidos
				String arrayFecha[] = reportDateString.split("/");	
				String dia = arrayFecha[0];
				String mes = arrayFecha[1];
				String anno = arrayFecha[2];
				//fecha desde la que se hace la consulta
				String fechaStringDesde = mes + "/" + dia + "/" + anno;
				//fecha hasta la que se hace la consulta
				String fechaStringHasta = "";
				GregorianCalendar calendario = new GregorianCalendar (Integer.parseInt(anno), Integer.parseInt(mes), 1);
				//obtengo el numero maximo de dias del mes
				int numDays = calendario.getActualMaximum(Calendar.DAY_OF_MONTH);
				//si es el ultimo dia del mes 12
				if (mes.equals(12) && dia.equals(String.valueOf(numDays)))
				{
					anno = String.valueOf(Integer.parseInt(anno) + 1);
					mes = "01";
					dia = "01";
				}
				//si es cualquier otro mes
				if (!mes.equals("12"))
				{
					//si es el ultimo dia del mes
					if (dia.equals(String.valueOf(numDays)))
					{
						mes = String.valueOf(Integer.parseInt(mes) + 1);
						dia = "01";
					}
					//si es cualquier otro dia
					else
					{
						dia = String.valueOf(Integer.parseInt(dia) + 1);
					}
				}
				fechaStringHasta = mes + "/" + dia + "/" + anno;
				Date fechaInformeDesde = formato.parse(fechaStringDesde);			
				Date fechaInformeHasta = formato.parse(fechaStringHasta);
				
				parameters.put("fechaInformeDesde", fechaInformeDesde);
				parameters.put("fechaInformeHasta", fechaInformeHasta);
Espero que todo esto le ayude a alguien, a mí me ha dado unos cuantos quebraderos de cabeza.

Un saludo y gracias por todo

Etiquetas: fechas, jasperreport, parametros
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 01:07.