Ir para conteúdo
Fórum Script Brasil
  • 0

DIFERENÇA ENTRE HORAS


axavier34

Pergunta

Bom dia amigos, novamente estou aqui solicitando a vocês uma ajuda ,no tange a trabalhar com data e hora com PHP e Mysql,

tenho em minha base esta estrutura

CREATE TABLE `chamados` (
`codigo` int(11) NOT NULL auto_increment,
`data_abertura` varchar(10) NOT NULL default '',
`data_fecha` varchar(10) NOT NULL default '',
`hora_abertura` varchar(5) NOT NULL default '',
`hora_fecha` varchar(5) NOT NULL default '',
`setor` varchar(15) NOT NULL default '',
`resumo` varchar(100) NOT NULL default '',
`descricao` text NOT NULL,
`solucao` text NOT NULL,
`tipo` varchar(25) NOT NULL default '',
`nome` varchar(50) NOT NULL default '',
`email` varchar(70) NOT NULL default '',
`status` varchar(12) NOT NULL default '',
`obs` text NOT NULL,
`tecnico` varchar(70) NOT NULL default '',
`img` varchar(100) default NULL,
`sms_benner` varchar(10) default NULL,
`chamado_benner` enum('0','1') default '0',
PRIMARY KEY (`codigo`)
) TYPE=MyISAM;
e conforme vocês podem ver os campos data_abertura, data_fecha , hora_abertura e hora_fecha estão definidos como VARCHAR e preciso listar por exemplo 1)O chamado 1 eu gastei 20 minutos para resolver, e o chamdo 3 gastei 3 dias e 1 hora para resolver 2)E depois uma média de tempo gasto pelos chamdos em um determinado período tentei fazer desta forma o exemplo 1 , mas não obtive resultado. teste_hora.html
<body>
<form action="teste_hora.php" method="post">
<table width="21%" border="1">
<tr>
<td width="51%">Data Inicial</td>
<td width="49%">Data Final</td>
</tr>
<tr>
<td><input name="dt1" type="text" size="10" maxlength="10" /></td>
<td><input name="dt2" type="text" size="10" maxlength="10" /></td>
</tr>
</table>

</form>
</body>
teste_hora.php
<body>
<?php

require_once ('config.php');
mysql_connect($Host, $Usuario, $Senha);
mysql_select_db($Base);

$dt1 = $_POST["data_ini"];
$dt2 = $_POST["data_final"];

$hora = "SELECT * FROM chamados WHERE data_abertura BETWEEN $dt1 AND $dt2 ORDER BY codigo " or die (mysql_error());

$time = mysql_query($hora);

$first_time= @mysql_fetch_object($time);

echo mysql_error();
?>
<table width="54%" border="1">
<tr>
<td width="33%">Código</td>
<td width="33%">Abertura</td>
<td width="33%">Fechamento</td>
<td width="34%">Total</td>
</tr>
<?php while ($Row = @mysql_fetch_object($first_time))
{
?>
<tr>
<td><?php $Row->codigo;?></td>
<td><?php $Row->hora_abertura;?></td>
<td><?php $Row->hora_fecha;?></td>
<td><?php $dife=(($Row->hora_abertura)-($Row->hora_fecha));?></td>
</tr>
<?php } ?>
</table>
</body>

Este são os códigos onde eu estou tentando fazer aparecer os dados que eu preciso no primeiro exemplo agora no segundo eu não tenho nem noção de como fazer.

Conto com a ajuda de vocês e desde já agradeço e que Deus abençõe a todos deste forum maravilhoso.

Att.

axavier34

Link para o comentário
Compartilhar em outros sites

4 respostass a esta questão

Posts Recomendados

  • 0
Oi, axavier34

Favor consultar Manual do MySQL. Ele já possui funções prontas.

Denis Courcy, obrigado pela dica dei uma estuda e achei alguns post em outros foruns e com ajuda de outras pessoas consegui chegar a estes scripts, fiz tb alteração no BD de dados

chamdo.sql

CREATE TABLE `chamado` (                                   
           `codigo` int(11) NOT NULL auto_increment,                
           `data_abertura` datetime default '0000-00-00 00:00:00',  
           `data_fecha` datetime default '0000-00-00 00:00:00',     
           `setor` varchar(15) NOT NULL default '',                 
           `resumo` varchar(100) NOT NULL default '',               
           `descricao` text NOT NULL,                               
           `solucao` text NOT NULL,                                 
           `tipo` varchar(25) NOT NULL default '',                  
           `nome` varchar(50) NOT NULL default '',                  
           `email` varchar(70) NOT NULL default '',                 
           `status` varchar(12) NOT NULL default '',                
           `obs` text NOT NULL,                                     
           `tecnico` varchar(70) NOT NULL default '',               
           `img` varchar(100) default NULL,                         
           `sms_benner` varchar(10) default NULL,                   
           `chamado_benner` enum('0','1') default '0',              
           PRIMARY KEY  (`codigo`)                                  
         ) TYPE=MyISAM
teste_hora.html
<html>
<body>
<form action="teste_hora1.php" method="post">
<table width="21%" border="1">
  <tr>
    <td width="51%">Data Inicial</td>
    <td width="49%">Data Final</td>
  </tr>
  <tr>
    <td><input name="dt1" type="text" size="10" maxlength="10" /></td>
    <td><input name="dt2" type="text" size="10" maxlength="10" /></td>
  </tr>
</table>

<p>
  <input type="submit" name="Enviar" value="Submit">
</p>
</form>
</body>
</html>
teste_hora1.php
<html>
<body>
<?php 

 include('config.php');
       

$dt1 = $_POST["dt1"];
$dt2 = $_POST["dt2"];

function revert($date){
return implode("-", array_reverse(explode("/", $date)));
}
    
$db = mysql_query("SELECT DATEDIFF(data_abertura, data_fecha) AS diff FROM chamado WHERE data_abertura BETWEEN '" . revert($_POST['dt1']) . "' AND '" . revert($_POST['dt2']) . "'");

//$time = mysql_query($hora);

//$first_time= mysql_fetch_object($time);
echo mysql_error();
?>
<table width="54%" border="1">
  <tr>
    <td width="33%">Código</td>
    <td width="33%">Abertura</td>
    <td width="33%">Fechamento</td>
    <td width="34%">Total</td>
  </tr>
  <?php  
  
  while($row = mysql_fetch_array($db)){
  $diferenca = date("H:i:s", $row['diff']);
  
?>
  <tr>
    <td><?php echo $Row->codigo;?></td>
    <td><?php echo $Row->hora_abertura;?></td>
    <td><?php echo $Row->hora_fecha;?></td>
    <td><?php echo  $diferenca;?></td>
  </tr>
  <?php } ?>
</table>
</body>
</html>

só que não funciona continua dando erro conforme abaixo

Você tem um erro de sintaxe no seu SQL próximo a '(data_abertura, data_fecha) AS diff FROM chamado WHERE data_abertura BETWEEN '20' na linha 1

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in c:\windows\serv-n\www\nivel\teste_hora1.php on line 31

Código Abertura Fechamento Total

Gostaria da ajuda de vocês para rsolver este problema

Desde já agradeço que Deus Abençõe a todos

Att.

axavier34

Link para o comentário
Compartilhar em outros sites

  • 0

Ola pessoal novamente aqui para solicita-lhe ajuda

achei o script abaixo e só acrescentei a instrução sql e o include o resto esta no formato original.

minha base de dados esta da seguinte forma e o Mysql que estou usando é o 4.0.24

CREATE TABLE `chamado` (                                   
           `codigo` int(11) NOT NULL auto_increment,                
           `data_abertura` datetime default '0000-00-00 00:00:00',  
           `data_fecha` datetime default '0000-00-00 00:00:00',     
           `setor` varchar(15) NOT NULL default '',                 
           `resumo` varchar(100) NOT NULL default '',               
           `descricao` text NOT NULL,                               
           `solucao` text NOT NULL,                                 
           `tipo` varchar(25) NOT NULL default '',                  
           `nome` varchar(50) NOT NULL default '',                  
           `email` varchar(70) NOT NULL default '',                 
           `status` varchar(12) NOT NULL default '',                
           `obs` text NOT NULL,                                     
           `tecnico` varchar(70) NOT NULL default '',               
           `img` varchar(100) default NULL,                         
           `sms_benner` varchar(10) default NULL,                   
           `chamado_benner` enum('0','1') default '0',              
           PRIMARY KEY  (`codigo`)                                  
         ) TYPE=MyISAM
Arquivo Original
<?

Function Diferenca($hora1, $hora2=""){

if($hora2==""){
$hora2 = date("H:i:s");
}

for($i=1;$i<=2;$i++){
${"horas".$i} = substr(${"hora".$i},0,2);
${"minutos".$i} = substr(${"hora".$i},3,2);
${"segundos".$i} = substr(${"hora".$i},6,2);
}

$dia = date(d);
$mes = date(m);
$ano = date(Y);

$segundos = mktime($horas2,$minutos2,$segundos2,$mes,$dia,$ano)-mktime($horas1,$minutos1,$segundos1,$mes,$dia,$ano);

return date("H:i:s",mktime(0,0,$segundos,$mes,$dia,$ano));

}


$data1 = "10:00:01";
$data2 = "19:59:00";

echo Diferenca($data1,$data2);
echo " diferença entre as horas.<br>";

?>
Resultado do arquivo original 09:58:59 diferença entre as horas. Arquivo alterado time.php
<?
include"config.php";

Function Diferenca($hora1, $hora2=""){

if($hora2==""){
$hora2 = date("H:i:s");
}

for($i=1;$i<=2;$i++){
${"horas".$i} = substr(${"hora".$i},0,2);
${"minutos".$i} = substr(${"hora".$i},3,2);
${"segundos".$i} = substr(${"hora".$i},6,2);
}

$dia = date(d);
$mes = date(m);
$ano = date(Y);

$segundos = mktime($horas2,$minutos2,$segundos2,$mes,$dia,$ano)-mktime($horas1,$minutos1,$segundos1,$mes,$dia,$ano);

return date("H:i:s",mktime(0,0,$segundos,$mes,$dia,$ano));

}
$sql = mysql_query("Select * from chamado where codigo='1'");
$oRow = mysql_fetch_object($sql);     
$dt1 = $oRow->data_abertura;
$dt2 = $oRow->data_fecha;
$data1 = $dt1;
$data2 = $dt2;

echo "$data1<br>";
echo "$data2<br>";
echo Diferenca($data1,$data2);
echo " diferença entre as horas.<br>";

?>

O resultado do arquivo alterado

2009-02-03 16:06:14

2009-02-04 08:25:33

00:00:00 diferença entre as horas.

Gostaria de contar com a juda de vocês novamente para me ajudar a enteder o que como funciona este script

Desde já agradeço a atenção e que Deus abençõe a todos.

Att.

axavier34.

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...