How to subtract a date from the current system date

Asked

Viewed 4,136 times

4

I want to subtract the current system date with the date that is saved in mysql. I insert the date into mysql via INSERT, manually, because I will not always use the current date to insert into the system.

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

It’s for a library system, where I enter the date the book was borrowed. in the book report, if the current date - the registration date is greater than or equal to 8 ( >= '8' ) should show that it is delayed by so many days. but I’m not getting it. 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";
        }
        ?>
  • 1

    What format do you receive from the bank at $pega_data = $linha ['data'];? In time: Why should we not use mysql type functions_*?

  • received in standard format ('Y/m/d')

  • 1

    So try to use $data_sistema = $linha [date("Y-m-d")];...

  • And you also need to Contact Datetime object (or use ceil as in Alan’s reply) before comparing the dates, I will post a more detailed answer, but I think the ideal is to do it directly in SQL itself, in the line of Willian’s reply...

3 answers

5

Do it right on Mysql

Read about the function Datediff

Look at this fiddle http://sqlfiddle.com/#! 9/5b7184/1 that I show you how to use and a functional example almost similar to your table.

Just for the sake of agility, follows snippet that takes the amount of days overdue:

[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
  • +1 The fiddle in this case helps a lot, because the snippet here does not support sql, but be sure to put the full code here, because the fiddle link can break and the answer will not be complete.

  • 1

    In fact, I’ll do it.

3


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

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

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'];

Takes a string from the bank, for example:

2010-11-19

And when it creates the current date on:

$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 pick up the first two numbers before the signal -, 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 way out will be:

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

See on IDEONE.

So what you need, in addition to leaving the formats equal, is to transform into an object Datetime 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 excerpt points out the result you seek:

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

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

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

See on IDEONE.

  • 1

    the wrong date format I noticed later and corrected. I will now turn into a Datetime object as you said and the appropriate changes and post later if I can, vlw.

  • I was able to do just as you explained to me @gustavox but it was an error, I’m not sure if it is a mistake or if you can hide it. appears all the encoding before my table. how to hide this encoding ????? I saved as pdf the page as it was, take a look there if you can, this saved in google drive, is ok file. https://drive.google.com/open?id=0B7MAXH1JQy95RUlxd21JUVN3R2s

  • Take out the var_dump, they are only for you to see the code output. @Guilhermehenrique

  • 1

    perfect. It worked right here. You saved my day. I started with php coding 2 weeks ago, and created a page since 0, with registration, reports, editing and deletion. this was the only part q could not do at all. vlw itself.

2

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

whereas the loan date is 2015-29-10 in 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; 
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.