How to subtract a date from the current system date

4

I want to subtract the current date from the system with the date that is written to mysql. I would like to insert the date in mysql through INSERT, manually, because I will not always use the current date to insert into the system.

I need to know how many days there is difference between the current date and the date you registered.

It's for a library system, where I enter the date the book was borrowed. in the book report, if the current date - the date of the record is greater than or equal to 8 (> = '8') should show that it is overdue for so many days. but I can not. I got lost in the middle of the code because of the dates.

fico grato se alguem puder me ajudar



    $sql_visualizar = mysql_query ("SELECT * FROM cadastro_alunos ORDER BY serie, numero, data");
    while ($linha = mysql_fetch_array ($sql_visualizar)){
        $pega_numero = $linha ['numero'];
        $pega_aluno = $linha ['nome'];
        $pega_serie = $linha ['serie'];
        $pega_n_livro = $linha ['n_livro'];
        $pega_livro = $linha ['livro'];
        $pega_emprestado = $linha ['emprestado'];
        $pega_data = $linha ['data'];
        $data_sistema = $linha [date("d-m-Y")];

        //aqui é para comparar as datas, se a data do emprestimo for maior que 8 dias (o sistema conta um dia a mais) realizar a função $pega_atraso
        $pega_atraso = $data_sistema - $pega_data;

    ?>
<?
if ($pega_emprestado == 'sim'){
?>
    //aqui fica os campos da tabela que uso, por isso estes não precisam aparecer aqui.
        <?

      //aqui é onde se encontra a função do atraso

if  ($pega_atraso >= '8'){

    echo "ENTREGA ATRASADA EM $pega_atraso dias";
    else 
        echo "No prazo de Leitura";
        }
        ?>
    
asked by anonymous 19.11.2015 / 03:24

3 answers

3

According to the clarification in the question comments, I see two problems in your code:

1 - You are getting the date of the database in ('Y/m/d') format, and comparing it with a date in ('d/m/Y') format;

2 - Instead of calculating the time difference between time objects ( Datetime for example) you are doing a mathematical operation between strings . When you do:

$pega_data = $linha ['data'];

You get a string from the database, for example:

  

2010-11-19

And when you create the current date at:

$data_sistema = $linha [date("d-m-Y")];

It also has a string:

  

19-11-2015

So when you do:

$pega_atraso = $data_sistema - $pega_data;

PHP will get the first two numbers before the - sign, and do the operation.

$pega_data = "19-11-2010";
$data_sistema = date("Y-m-d");

$pega_atraso = $data_sistema - $pega_data;

var_dump($pega_data);
var_dump($data_sistema);
var_dump($pega_atraso);

And the output will be:

string '19-11-2010' (length=10)
string '2015-11-19' (length=10)
int 1996 // 2015 - 19

See the IDEONE .

So what you need, in addition to leaving the same formats, is to transform into a Datetime object before subtracting:

$pega_data = "2010-11-19";
$data_sistema = date("Y-m-d");

$pega_data_Time = new DateTime($pega_data);
$data_sistema_Time = new DateTime($data_sistema);

$pega_diferenca = $data_sistema_Time->diff($pega_data_Time);

var_dump($pega_data);
var_dump($data_sistema);
var_dump($pega_diferenca);

The output will contain the following object DateInterval :

string '2010-11-19' (length=10)
string '2015-11-19' (length=10)
object(DateInterval)[3]
  public 'y' => int 5
  public 'm' => int 0
  public 'd' => int 0
  public 'h' => int 14
  public 'i' => int 51
  public 's' => int 35
  public 'weekday' => int 0
  public 'weekday_behavior' => int 0
  public 'first_last_day_of' => int 0
  public 'invert' => int 0
  public 'days' => int 1826
  public 'special_type' => int 0
  public 'special_amount' => int 0
  public 'have_weekday_relative' => int 0
  public 'have_special_relative' => int 0

Where this section points to the result you are looking for:

  public 'y' => int 5
  public 'm' => int 0
  public 'd' => int 0

In this case, 5 years, 0 months and 0 days, which can be obtained through the -> operator, like this:

echo "A diferença de tempo é de " . $pega_diferenca->y . " anos , " .  $pega_diferenca->m . " meses, e " . $pega_diferenca->d . " dias.";

See the IDEONE .

    
19.11.2015 / 18:05
5

Do it right in MySQL

Read about datediff

See this fiddle link that I show you how to use and a functional example almost similar to your table.

Just for the sake of agility, the snippet that takes the number of days in arrears follows:

[SQL Fiddle] [1]

MySQL 5.6 Schema Setup :

create table cadastro_alunos (
  id int primary key auto_increment,
  numero int not null,
  data datetime not null default current_timestamp
);

insert into cadastro_alunos (numero, data) values
(1, '2015-11-19 00:00:00'),
(2, '2015-11-18 00:00:00'),
(3, '2015-11-17 00:00:00'),
(4, '2015-11-10 00:00:00'),
(5, '2015-11-9 00:00:00'),
(6, '2015-11-1 00:00:00'),
(7, '2015-08-21 00:00:00');

Query 1 :

select
  id,
  numero,
  data,
  datediff(now(), data) as dias_em_atraso
from cadastro_alunos
    
19.11.2015 / 03:39
2

In PHP the mktime() and time() functions can help you:

Considering that the loan date as 2015-29-10 had a very didactic way, we would have:

<?php 
    $data1 = "2015-10-29"; 
    $data1 = explode("-", $data1); //Transforma em array
    $data1 = mktime(0, 0, 0, $data1[1], $data1[2], $data1[0]); // Utiliza o array para pegar o unix timestamp da data em questão

    $data2 = time(); //Pega o unix timestamp da momento atual

    $diferenca = ceil(($data2-$data1)/86400); // faz a diferença dividida por 86400 para termos o resultado em dias e arredondamos para cima com ceil
    echo $diferenca; 
?>
    
19.11.2015 / 03:46