How to check if Data X is newer than Data Y? [duplicate]

1

I have the following variables:
$dt_local : which is saving BD value;
$dt_remoto : that is saving value from an external source;
So far all great, I need to compare the two and keep the most current date in the DB, both variables are coming as String .

How can I solve it faster and easier?

    
asked by anonymous 03.05.2017 / 19:41

2 answers

3

Assuming you have these dates in some defined format, you can use the DateTime class. of PHP:

$dt_local = DateTime::createFromFormat('d-m-Y', '03-04-2017');
$dt_remoto = DateTime::createFromFormat('d-m-Y', '01-04-2017');

if ($dt_local > $dt_remoto) {
    echo "Local é mais recente", PHP_EOL;
} else if ($dt_local < $dt_remoto) {
    echo "Remoto é mais recente", PHP_EOL;
} else {
    echo "Datas são iguais", PHP_EOL;
}

The output would be: Local é mais recente .

If the date can be any pattern defined in documentation of PHP, use the date itself class constructor:

$dt_local = new DateTime('03-04-2017');
$dt_remoto = new DateTime('01-04-2017');

if ($dt_local > $dt_remoto) {
    echo "Local é mais recente", PHP_EOL;
} else if ($dt_local < $dt_remoto) {
    echo "Remoto é mais recente", PHP_EOL;
} else {
    echo "Datas são iguais", PHP_EOL;
}

In theory, any format provided in the table below will be accepted by the application.

    
03.05.2017 / 20:07
0

One way to check is by using the max ( $valor1 , $valor2 ) function (PHP 4, PHP 5, PHP 7)

where $ value1 and $ value2 are compatible values in the format dd / mm / yyyy or dd-mm-yyyy.

Manual

<?php
function inverteData($data){
    if(count(explode("/",$data)) > 1){
        return implode("-",array_reverse(explode("/",$data)));
    }elseif(count(explode("-",$data)) > 1){
        return implode("/",array_reverse(explode("-",$data)));
    }
}

if  (($_POST["dt_local"])&&($_POST["dt_remoto"])){

    $dt_local=inverteData($_POST["dt_local"]);  

    $dt_remoto=inverteData($_POST["dt_remoto"]);

    if ($dt_local!=$dt_remoto){
       $maior = max(array($dt_local,$dt_remoto));
       echo inverteData($maior);
    }else{
       echo "as datas são iguais";;
    } 
}
?>
    
04.05.2017 / 00:05