Ver Mensaje Individual
  #11 (permalink)  
Antiguo 23/04/2015, 00:30
eferion
 
Fecha de Ingreso: octubre-2014
Ubicación: Madrid
Mensajes: 1.212
Antigüedad: 9 años, 6 meses
Puntos: 204
Respuesta: Validar 2 fechas guardadas en variables char [C]

Cita:
Iniciado por vangodp Ver Mensaje
tenga en cuenta que ni todos los meses tienen 28 días. El calculo es aproximado y puede fallar. Aun así no conozco nada más compacto.
Se puede conseguir un cálculo sin error con un par de cambios:

Código C:
Ver original
  1. int comparar(struct Fecha fechaDada, struct Fecha fechaInicio, struct Fecha fechaFin)
  2. {
  3.   unsigned long fecha = fechaDada.anio * 10000 + (fechaDada.mes * 100) + fechaDada.dia;
  4.   unsigned long inicio = fechaInicio.anio * 10000 + (fechaInicio.mes * 100) + fechaInicio.dia;
  5.   unsigned long fin = fechaFin.anio * 10000 + (fechaFin.mes * 100) + fechaFin.dia;
  6.  
  7.   if ( fecha >= inicio && fecha <= fin )
  8.   {
  9.     return 1;
  10.   }else{
  11.     return 0;
  12.   }
  13. }

Claro que también puedes pasarlo a una estructura tm y comparar:

Código C:
Ver original
  1. time_t FechaToTime( struct Fecha* fecha )
  2. {
  3.   struct tm info;
  4.  
  5.   info.tm_sec = 0;
  6.   info.tm_min = 0;
  7.   info.tm_hour = 0;
  8.   info.tm_mday = fecha->dia;
  9.   info.tm_mon = fecha->mes - 1;
  10.   info.tm_year = fecha->anio - 1900;
  11.   info.tm_isdst = -1;
  12.  
  13.   return mktime( &info );
  14. }
  15.  
  16. int comparar(struct Fecha fechaDada, struct Fecha fechaInicio, struct Fecha fechaFin)
  17. {
  18.    time_t fecha = FechaToTime( &fechaDada );
  19.    time_t inicio = FechaToTime( &fechaInicio );
  20.    time_t fin = FechaToTime( &fechaFin );
  21.  
  22.    if ( fecha >= inicio && fecha <= fin )
  23.   {
  24.     return 1;
  25.   }else{
  26.     return 0;
  27.   }
  28. }

Y luego, como tercera opción, siempre puedes hacer las comparaciones "a pelo":

Código C:
Ver original
  1. // el return puede ser:
  2. // == 0 -> Las dos fechas son iguales
  3. // > 0  -> fecha1 > fecha2
  4. // < 0  -> fecha1 < fecha2
  5. int comparar2Fechas( struct Fecha* fecha1, struct Fecha* fecha2 )
  6. {
  7.   int to_return =  fecha1->anio - fecha2->anio;
  8.  
  9.   if( to_return == 0 )
  10.     to_return = fecha1->mes - fecha2->mes;
  11.  
  12.   if( to_return == 0 )
  13.     to_return = fecha1->dia - fecha2->dia;
  14.  
  15.   return to_return;
  16. }
  17.  
  18. int comparar(struct Fecha fechaDada, struct Fecha fechaInicio, struct Fecha fechaFin)
  19. {
  20.   int to_return = 0;
  21.  
  22.   if( comparar2Fechas( &fechaDada, &fechaInicio ) >= 0 )
  23.   {
  24.     if( comparar2Fechas( &fechaDada, &fechaFin ) <= 0 )
  25.       to_return = 1;
  26.   }
  27.  
  28.   return to_return;
  29. }

Será por falta de alternativas :)

Un saludo