0

Successfully fetch "wdate" from MySQL and print the date in format Y:m:d H:i:s, my goal is to input "wdate" in the second code "function" is this possible or completely wrong?

<?php 

$sql = "SELECT wdate, DATE_FORMAT(wdate,'%Y/%m/%d %H:%i:%s') AS wdate 
            FROM watering
            ORDER BY id 
            DESC limit 1";
$result = $conn->query($sql);

    if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
$recoredDate = $row["wdate"];

            }
    } else {
      echo "<h1><b>Database is empty</b></h1>";
    }
?>

This is the second part calculating the difference like this:

<?php

 function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now'; }    ?>  



   <?php echo ($recoredDate);?> <!-- Result from Database -->
 <?php echo time_elapsed_string('2021-01-28 20:46:25'); ?> <!-- Result from function -->
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 2
    You shouldn't have `wdate` twice in your `SELECT`. Are you not storing in as `DATETIME`? – Steven Jan 29 '21 at 22:39
  • If you want the date in `Y:m:d` format, why are you using `%Y/%m/%d`? Do you want `:` or `/` between the date components? – Barmar Jan 29 '21 at 22:40
  • 1
    Why aren't you using PHP's built-in [`DateInterval`](https://www.php.net/manual/en/class.dateinterval.php`) class? – Barmar Jan 29 '21 at 22:42
  • @Barmar not sure what you mean, the OP is using the `DateInterval` class? (That's the object/class that `DateTime::diff`returns?) – Steven Jan 29 '21 at 23:20
  • @Barmar also, I believe that (i.e. the format required) to be a typo as the OP appears to be using the returned date in as the seed for a `new DateTime` object? – Steven Jan 29 '21 at 23:22
  • Oh, I misread, I thought he was writing his own interval code. – Barmar Jan 29 '21 at 23:25

1 Answers1

2

The main question appears to be:

How to call the custom function with the date returned from the database?

The answer to which is replace this line...

$recoredDate = $row["wdate"];

...with this line...

echo time_elapsed_string($row["wdate"], true);

...if you simply want to output the difference.

Alternatively, with your code above...

echo time_elapsed_string($recoredDate, true);

Note: this assumes that the function and the code are in the same file/scope

Additional info

Let's assume that you have stored the wdate date in a DateTime field in your database. In that case the format is already Y-m-d H:i:s which is what you want to feed into your function, so we can just select it and not have to try and reformat it...

Updated code

I have updated your code with the appropriate query and output:

$sql = "
    SELECT wdate
    FROM watering
    ORDER BY id DESC
    LIMIT 1
";

$result = $conn->query($sql);

if($result->num_rows) {
    while($row = $result->fetch_assoc()){
        echo "Last watering: ", time_elapsed_string($row["wdate"], 1);
    }
}
else{
    echo "<h1><b>Database is empty</b></h1>";
}

I've also updated your function a bit:

function time_elapsed_string(string $inputTimestamp, bool $full = false) : string
{
    $currentTime    = new DateTime;
    $compareTime    = new DateTime($inputTimestamp);
    $timeDifference = $currentTime->diff($compareTime);

    $timeDifference->w  = floor($timeDifference->d / 7);
    $timeDifference->d %= 7;

    $datePartArray = [
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    ];

    $output = [];
    foreach($datePartArray as $datePart => $description){
        if($timeDifference->$datePart){
            $output[] = "{$timeDifference->$datePart} {$description}"
                        . ($timeDifference->$datePart > 1 ? 's' : '');
        }
    }

    if (!$full){
        $output = [ $output[0] ];
    }

    return $output ? implode(', ', $output) . ' ago' : 'just now'; 
} 

If wdate isn't in the right format then we're still just going to select it from the database as above and we'll amend the code in the function to accommodate...

Of course if this is the case then I don't know what format you have it in (you haven't said as yet) so you will have to amend as needed. But effectively we're going to change this line:

$compareTime    = new DateTime($inputTimestamp);

To something like:

// Date/Time: 15/01/2021 12:03
$compareTime = DateTime::createFromFormat("d/m/Y H:i", $inputTimestamp);

// Unix timestamp: 1610757655
$compareTime = DateTime::createFromFormat("U", $inputTimestamp);
// OR...
$compareTime = new DateTime("@".$inputTimestamp);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Steven
  • 6,053
  • 2
  • 16
  • 28
  • FYI, that function was taken from https://stackoverflow.com/a/18602474/1839439 – Dharman Jan 30 '21 at 00:58
  • the OP obviously used already written code from stackoverflow, the OP also was lead to this article (code) from @Dharman, so thank you! Steven, if you want to see the original code that I wrote please get in touch and I will provide it. It's working but not as good as this one above! Best Wishes – Inna Ivanova Jan 30 '21 at 16:17
  • @InnaIvanova I meant no offence; only that my answer would change (from step-by-step examples moving toward generalised ideas) based on the experience/specific knowledge/skillset of the asker, Your question confused me because I couldn't tell where on that scale I should aim to answer! If the original code is different from that shown by Dharman's screenshot then I'd be interested to see it, maybe as a link to one of the many _fiddle_ style websites – Steven Jan 30 '21 at 16:51
  • 1
    @InnaIvanova did this answer the question or did I misunderstand somewhere? – Steven Jan 30 '21 at 16:51