Ir al contenido


Foto

Obtener el numero de semanas entre dos fechas [PHP]


  • Por favor identifícate para responder
7 respuestas en este tema

#1 vasquez

vasquez

    Member

  • Miembros
  • PipPip
  • 14 mensajes

Escrito 23 octubre 2011 - 07:41

Buenas Noches.
Mi consulta es la siguiente:
Tengo un formulario llamado lote, su Insert Into y su Extraer. En el formulario hay un campo en el que se introduce la fecha mediante un calendario. Necesito que cuando se realize la consulta, aparesca en un campo llamado edad actual, el tiempo en semanas a partir de la fecha que se introdujo en el formulario.
tengo un codigo muy corto que muestra el tiempo en semanas, pero lo malo es que muestra las semanas desde el primer dia del año en curso, y yo necesito que me muestre el tiempo en semanas, a partir de una fecha que se de como inicial.
El otro problema es que al correr este codigo  aparce el siguiente mensaje:
Strict Standards: DateTime::__construct() [datetime.--construct]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Paris' for '1.0/no DST'
El punto àlgido del asunto es como introduzco este còdigo en el extraer para que se manifieste al realizar la consulta.
Les adjunto el script del formulario, su Insert, el extraer  y  el de mostrar las semanas.
Por fabor le ruego leer  el codigo para que me puedan dar algun consejo.

FORMULARIO LOTE




html5
  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2.     <head>
  3.       <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  4.         <head><title>       
  5.         FORMULARIO LOTE
  6.         </title>
  7.         <link  rel="stylesheet" href="../herramientas/calendario/system.css" />
  8.         <script type="text/javascript" src="../herramientas/calendario/zapatec.js"></script>
  9.         <script type="text/javascript" src="../herramientas/calendario/calendar.js"></script>
  10.         <script type="text/javascript" src="../herramientas/calendario/calendar-es.js"></script>
  11.         <link rel="stylesheet" type="text/css" href="estilos/formscss.css">
  12.         <link rel="Stylesheet" href="estilos/formscss.css">
  13.   </head>
  14.   <body>
  15.       <form name="lote" method="post"  action="form_lote.php" onSubmit="return validar(this)">
  16.         <table  align="center" class="cuerpo" cellspacing="0" cellpadding="0">
  17.             <tr>
  18.               <td>
  19.                   <table width="100%" border="1"  align="center" cellpadding="0" cellspacing="0" class="cuerpo3">
  20.                     <tr class="titulo1">
  21.                         <td align="center">Nro. lote</td>
  22.                         <td align="center">Fecha ingreso</td>
  23.                         <td align="center">Edad al ingresar</td>
  24.                     </tr>
  25.                     <tr>
  26.                         <td align="center" > <input name="lote" class="estil_caja" id="lote" type='text' size='10' title='lote'> </td>
  27.                         <td align="center" valign="middle" >
  28.                           <input id="fch_ingreso" name="fch_ingreso" class="estil_caja" type="text" size="8%"  title='Fecha de ingreso' readonly/>
  29.                         <img id='btn_fch_ingreso' title="Calendario para Seleccionar la Fecha de ingreso" src='../herramientas/calendario/calendario_1.gif' border='0' style="cursor:pointer" />
  30.                         </td>
  31.                         <td align="center" ><input name="edad" class="estil_caja" type='text' size='10' title='edad'></td> 
  32.                     </tr>
  33.                 </table>
  34.               <p>
  35.                   <tr>
  36.                     <td colspan="5" align="center" >
  37.                       <input type='submit' name='boton' class='boton' value='Guardar'>
  38.                   </tr></p>
  39.         </table>
  40.       </form>
  41.       <script type="text/javascript">
  42.         Zapatec.Calendar.setup({
  43.             weekNumbers      : false,
  44.             showOthers      : true,
  45.             showsTime      : false,
  46.             step        : 1,
  47.             electric      : true,
  48.             inputField      : "fch_ingreso",
  49.             button        : "btn_fch_ingreso",
  50.             timeFormat      : 24,
  51.             timeInterval  : 05,
  52.             ifFormat      : '%Y-%m-%d',
  53.             daFormat      : '%Y-%m-%d'
  54.           });
  55.       </script>
  56.   </body>
  57. </html>



INSERT INTO FORMULARIO LOTE



php
  1. <html xmlns="http://www.3w.org/1999/xhtml">
  2. <head>
  3. <meta http-equiv="content-type" content="text/html:charset=utf-8"/>
  4. <title>form_lote</title>
  5. </head>
  6. <body>
  7. <?php
  8. $id_lote=$_POST["id_lote"];
  9. $lote=$_POST["lote"];
  10. $fch_ingreso=$_POST["fch_ingreso"];
  11. $edad =$_POST["edad"];
  12. //establesco la coneccion
  13. $conectar=mysql_connect("localhost","root","sena");
  14. mysql_select_db("tecnoavicola19",$conectar);
  15. mysql_query("INSERT INTO lote(lote,fch_ingreso,edad)
  16. values('$lote','$fch_ingreso','$edad',)");
  17. mysql_close($conectar);
  18. //header("location: formulario_lote.php");
  19. print "<meta http-equiv=Refresh content="0 ; url=formulario_lote.php">";
  20. ?>
  21. </body>
  22. </html>



EXTRAER FORMULARIO LOTE



php
  1. <?php
  2. $conectar=mysql_connect("localhost","root","sena");
  3. mysql_select_db("tecnoavicola19",$conectar);
  4. $resultado = mysql_query("SELECT * FROM lote ORDER BY id_lote");
  5. echo "<table width='100%' height'100%' border='' bgcolor=''>
  6. <tr bgcolor='#5F9EA0'><td>NRO. LOTE</td><td>FECHA INGRESO</td><td>EDAD ACTUAL </td></tr>";
  7. while($fila = mysql_fetch_array($resultado))
  8. {
  9. echo "<tr>
  10.         <td> $fila[lote]</td>
  11.         <td> $fila[fch_ingreso]</td>
  12.         <td>$fila[edad]</td>
  13. }
  14. echo "</table>";
  15. mysql_close($conectar);
  16. ?>
  17. </td>
  18. </tr>
  19. </table>



CALCULO DE TIEMPO EN SEMANAS



php
  1. <?php
  2. $fecha = new DateTime();
  3. $semana = $fecha->format('W'); // semana del año
  4. $semana  ;
  5. echo ': '.$semana; // semana del año
  6. ?>


  • 0

#2 enecumene

enecumene

    Webmaster

  • Administrador
  • 7.419 mensajes
  • LocationRepública Dominicana

Escrito 24 octubre 2011 - 10:07

Hola, te voy a dejar un modo de calcular las semanas que hay entre dos fechas, lo hare de memoria y puede tener algun bugs, pero te dara una idea de donde partir:



php
  1. $fecha_desde = "10-01-2011"; //Formato MM-DD-YYYY
  2. $fecha_hasta = mktime(); //La fecha actual en formato timestamp
  3.  
  4. //Dividimos la fecha inicial en Mes, Ano y Dia para luego convertirlo en timestamp
  5.  
  6. $dividefecha = explode("-", $fecha_desde);
  7.  
  8. // $dividefecha[0] = Mes
  9. // $dividefecha[1] = Dia
  10. // $dividefecha[2] = Ano
  11.  
  12. $fecha_previa = mktime(0, 0, $dividefecha[0], $dividefecha[1], $dividefecha[2]); //Convertimos $fecha_desde en formato timestamp
  13.  
  14. $segundos = $fecha_previa - $fecha_hasta; // Obtenemos los segundos entre esas dos fechas
  15. $segundos = abs($segundos); //en caso de errores
  16.  
  17. $semanas = floor($segundos / 604800); //Obtenemos las semanas entre esas fechas.
  18.  
  19. echo "hay " . $semanas;



Espero te sirva,

Saludos.
  • 0

#3 vasquez

vasquez

    Member

  • Miembros
  • PipPip
  • 14 mensajes

Escrito 28 octubre 2011 - 08:53

Agradesco tu atencion
He insertado el còdigo que me enviaste en la cabecera de ver_lote, y he definido la variable $fecha_desde, asì:
$fecha_desde = "$fila[fch_ingreso]";  y  $semanas  lo reubiquè. Entonces el codigo de ver_lote queda asì:

ver_lote



php
  1. <?php
  2. $fecha_desde = "fch_ingreso"; //Formato MM-DD-YYYY
  3. mysql_select_db("tecnoavicola19",$conectar);
  4. $resultado = mysql_query("SELECT * FROM lote ORDER BY id_lote");
  5. echo "<table width='100%' height'100%' border='' bgcolor=''>
  6. <tr bgcolor='#5F9EA0'><td>NRO. LOTE</td><td>FECHA INGRESO</td><td>EDAD ACTUAL </td></tr>";
  7. while($fila = mysql_fetch_array($resultado))
  8. {
  9. echo
  10. "<tr>
  11.         <td> $fila[lote]</td>       
  12.         <td> $fila[fch_ingreso]</td>
  13.         <td>$fila[edad]</td>
  14.         <td> $semanas</td>
  15. }
  16. echo "</table>";
  17. mysql_close($conectar);
  18. ?>
  19. </td>
  20. </tr>
  21. </table>
  22.  
  23. $conectar=mysql_connect("localhost","root","sena");
  24. mysql_select_db("tecnoavicola19",$conectar);
  25. $resultado = mysql_query("SELECT * FROM lote ORDER BY id_lote");
  26. echo
  27. "<table width='100%' height'100%' border='' bgcolor=''>
  28. <tr bgcolor='#5F9EA0'>
  29. <td>NRO. LOTE</td><td>FECHA INGRESO</td><td>EDAD ACTUAL </td><td>SEMANAS</td></tr>";
  30. while($fila = mysql_fetch_array($resultado))
  31. {
  32. echo
  33. "<tr>       
  34. <td> $fila[lote]</td><td> $fila[fch_ingreso]</td><td>$fila[edad]</td><td>$semanas;</td>
  35. }
  36. echo "</table>";mysql_close($conectar);
  37. ?>
  38. </td>
  39. </tr>
  40. </table>




cuando intento correr la aplicación aparece este mensaje


delphi
  1. Parse error: syntax error, unexpected '=' in C:\AppServ\www\tecnoavicola_AppServer1\modelos\ver_lote.php on line 5




O  sea  la  linea  donde  se encuentra la variable $semanas.
Agradezco tu  atencion
  • 0

#4 enecumene

enecumene

    Webmaster

  • Administrador
  • 7.419 mensajes
  • LocationRepública Dominicana

Escrito 01 noviembre 2011 - 07:30

Hola, el error lo dice muy claro, te falta un "=" en la linea numero 5, lo tienes asi:



php
  1. echo "<table width='100%' height'100%' border='' bgcolor=''>



y deberia ser asi:



php
  1. echo "<table width='100%' height='100%' border='' bgcolor=''>



Saludos.

  • 0

#5 Bish0p

Bish0p

    Advanced Member

  • Miembros
  • PipPipPip
  • 64 mensajes
  • LocationMéxico, DF

Escrito 01 noviembre 2011 - 05:08

Que tal,

aparte del error que te menciona enecumene,  en tu ciclo en donde haces el recorrido te hace falta cerrar el echo



delphi
  1. while($fila = mysql_fetch_array($resultado))
  2. {
  3. echo
  4. "<tr>       
  5. <td> $fila[lote]</td><td> $fila[fch_ingreso]</td><td>$fila[edad]</td><td>$semanas;</td>
  6. }




Asi:



delphi
  1. while($fila = mysql_fetch_array($resultado))
  2. {
  3. echo "<tr>
  4.                 <td> $fila[lote]</td>       
  5.                 <td> $fila[fch_ingreso]</td>
  6.                 <td>$fila[edad]</td>
  7.                 <td> $semanas</td>
  8.         </tr>
  9.         ";
  10. }




y ademas estas lineas sobran despues de que haces el cierre de tu conexion (mysql_close($conectar);)

</td>
</tr>
</table>


Saludos

  • 0

#6 vasquez

vasquez

    Member

  • Miembros
  • PipPip
  • 14 mensajes

Escrito 12 noviembre 2011 - 09:04

Hola disculpen  la tardanza en responder sus  mensajes.
He corregido los puntos que me han indicado y este es el còdigo final en el extraer de lote.

ver_lote.php

<?php

$fecha_desde = "10-01-2011"; //Formato MM-DD-YYYY$
$fecha_hasta = mktime(); //La fecha actual en formato timestamp
//Dividimos la fecha inicial en Mes, Ano y Dia para luego convertirlo en timestamp
$dividefecha = explode("-", $fecha_desde);
// $dividefecha[0] = Mes
// $dividefecha[1] = Dia
// $dividefecha[2] = Ano
$fecha_previa = mktime(0, 0, $dividefecha[0], $dividefecha[1], $dividefecha[2]); //Convertimos $fecha_desde en formato timestamp
$segundos = $fecha_previa - $fecha_hasta; // Obtenemos los segundos entre esas dos fechas
$segundos = abs($segundos); //en caso de errores
$semanas = floor($segundos / 604800); //Obtenemos las semanas entre esas fechas.
echo "hay " . $semanas;

//include("conecta.php");
$conectar=mysql_connect("localhost","root","sena");
mysql_select_db("tecnoavicola19",$conectar);

//$resultado = mysql_query("SELECT * FROM lote ORDER BY id_lote");
$_pagi_sql =("SELECT * FROM lote ORDER BY id_lote");


//cantidad de resultados por página (opcional, por defecto 20)
$_pagi_cuantos = 3;

//Incluimos el script de paginación. Éste ya ejecuta la consulta automáticamente
include("paginator.inc.php");


echo "<table width='100%' height='100%' border='' bgcolor=''>
   
    <tr bgcolor='#5F9EA0'><td>NRO. LOTE</td><td>FECHA INGRESO</td><td>NUMERO AVES</td><td>LINEAS</td><td>EDAD FECHA INGRESO</td><td>OBSERVACIONES</td><td>SEMANAS</td></tr>";

//while($fila = mysql_fetch_array($resultado))
while($fila = mysql_fetch_array($_pagi_result))
{
echo "<tr>
         
        <td> $fila[lote]</td>
        <td> $fila[fch_ingreso]</td>
        <td>$fila[numero]</td>
        <td> $fila[lineas]</td>
        <td>$fila[edad]</td>
        <td>$fila[observaciones]</td>
        <td> $semanas</td>
        </tr>";

}
//Incluimos la barra de navegación
echo"<p>".$_pagi_navegacion."</p>";

echo "</table>";
mysql_close($conectar);
?>


<p align="center" HEIGHT="5%" width="18%" ><input id="registro" name="Imprimir" type="button" value="imprimir" style='cursor:pointer' onClick="window.print()"></p>


Resulta que cuando hago la consulta, en la cabecera de esta, aparece el siguiente mensaje:



delphi
  1. Strict Standards: mktime() [function.mktime]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for '-5.0/no DST' instead in C:\AppServ\www\tecnoavicola_AppServer1\modelos\ver_lote.php on line 5
  2.  
  3. Strict Standards: mktime() [function.mktime]: You should be using the time() function instead in C:\AppServ\www\tecnoavicola_AppServer1\modelos\ver_lote.php on line 5
  4.  
  5. Strict Standards: mktime() [function.mktime]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for '-5.0/no DST' instead in C:\AppServ\www\tecnoavicola_AppServer1\modelos\ver_lote.php on line 11
  6. hay 242



Este dato "hay 242" es el que aparece en el campo semanas de la consulta, pero es el mismo para todas las fechas que se estipulen como inicial, hasta la presente fecha, y el objetivo es que aparezca el tiempo en semanas especifico para cada espacio de tiempo comprendido entre las variables  $fecha_desde y  $fecha_hasta.
Agradezco su atencion.
  • 0

#7 enecumene

enecumene

    Webmaster

  • Administrador
  • 7.419 mensajes
  • LocationRepública Dominicana

Escrito 14 noviembre 2011 - 07:17

Pues hagamos una pequena correcion, OJO, lo hice al vuelo, puede contener errores y causar bugs 

function Semanas($fecha_desde, $fecha_hasta)
{
   
    $divide_ini = explode("-", $fecha_desde);
    $divide_fin = explode("-", $fecha_hasta);
   
    $fecha_ini = mktime(0, 0, $divide_ini[0], $divide_ini[1], $divide_ini[2]);
    $fecha_fin = mktime(0, 0, $divide_fin[0], $divide_fin[1], $divide_fin[2]);

    $segundos = $fecha_ini - $fecha_fin; // Obtenemos los segundos entre esas dos fechas
    $segundos = abs($segundos); //en caso de errores
    $semanas = floor($segundos / 604800); //Obtenemos las semanas entre esas fechas.
   
    echo "Hay " . $semanas;

}

//include("conecta.php");
$conectar=mysql_connect("localhost","root","sena");
mysql_select_db("tecnoavicola19",$conectar);

//$resultado = mysql_query("SELECT * FROM lote ORDER BY id_lote");
$_pagi_sql =("SELECT * FROM lote ORDER BY id_lote");


//cantidad de resultados por página (opcional, por defecto 20)
$_pagi_cuantos = 3;

//Incluimos el script de paginación. Éste ya ejecuta la consulta automáticamente
include("paginator.inc.php");


echo "<table width='100%' height='100%' border='' bgcolor=''>

    <tr bgcolor='#5F9EA0'><td>NRO. LOTE</td><td>FECHA INGRESO</td><td>NUMERO AVES</td><td>LINEAS</td><td>EDAD FECHA INGRESO</td><td>OBSERVACIONES</td><td>SEMANAS</td></tr>";

//while($fila = mysql_fetch_array($resultado))
while($fila = mysql_fetch_array($_pagi_result))
{
echo "<tr>

        <td>" . $fila['lote'] . "</td>
        <td>" .  $fila['fch_ingreso']  . "</td>
        <td>" . $fila['numero'] . "</td>
        <td>" . $fila['lineas'] . "</td>
        <td>" . $fila['edad'] . "</td>
        <td>" . $fila['observaciones'] . "</td>
        <td>";
        $fecha_actual = date(m-d-Y);
        Semanas($fila['fch_ingreso'],$fecha_actual);
      echo "</td>
        </tr>";

}
//Incluimos la barra de navegación
echo"<p>".$_pagi_navegacion."</p>";

echo "</table>";
mysql_close($conectar);
?>


<p align="center" HEIGHT="5%" width="18%" ><input id="registro" name="Imprimir" type="button" value="imprimir" style='cursor:pointer' onClick="window.print()"></p>


Nos comentas.

Saludos.
  • 0

#8 vasquez

vasquez

    Member

  • Miembros
  • PipPip
  • 14 mensajes

Escrito 14 noviembre 2011 - 02:48

Gracias por responder
He puesto el còdigo que enviaste y hay dos problemas.
Al hacer la consulta, en el campo semanas, que es donde debe aparecer el calculo, aparece este mensaje del sistema:
Strict Standards: date() [function.date]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for '-5.0/no DST' instead in C:\AppServ\www\tecnoavicola_AppServer1\modelos\ver_lote.php on line 46
Este corresponde a esta linea de  codigo:
<td>";$fecha_actual = date(m-d-Y); Semanas($fila['fch_ingreso'],$fecha_actual);echo "</td>

Strict Standards: mktime() [function.mktime]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for '-5.0/no DST' instead in C:\AppServ\www\tecnoavicola_AppServer1\modelos\ver_lote.php on line 8
Este corresponde a esta linea de  còdigo:
$fecha_ini = mktime(0, 0, $divide_ini[0], $divide_ini[1], $divide_ini[2]);

Strict Standards: mktime() [function.mktime]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for '-5.0/no DST' instead in C:\AppServ\www\tecnoavicola_AppServer1\modelos\ver_lote.php on line 9
Este corresponde a esta linea de còdigo:
$fecha_fin = mktime(0, 0, $divide_fin[0], $divide_fin[1], $divide_fin[2]);

El otro problema es que el calculo no es muy acertado pues al darle una fecha inicial como 2011-11-01 y como fecha final 2011-11-14 el calculo da:  Hay 47.

Y tengo esta situacion:
Resulta que el formulario lote se utiliza para registrar el ingreso de un lote de aves ponedoras,  en uno de sus campos se registra la edad con la que ingresan estas aves al galpon, que por lo general es de 15 a 17 semanas. Al obtener el calculo de tiempo en semanas desde una fecha de ingreso, por ejemplo 2011-05-01 a una fecha final  2011-11-01 nos deberìa dar 29 semanas. Ahora, el lote ingresò con 17 semanas, o sea que a la fecha de la consulta debe tener 46 semanas, y esto es lo que debe aparecer en el campo semanas al momento de realizar la consulta.
Espero no abuzar de su atencion.
Gracias.
  • 0




IP.Board spam blocked by CleanTalk.