duanmu5641 2018-08-07 00:16
浏览 40

很难理解如何在PHP中操作日期和时间

I'm really not grasping how dates and times get formatted in PHP for use in mathematical equations. My goal is this;

Get a date and time from the database;

// Get array for times in
$sth = mysqli_query($conn,"SELECT * FROM ledger ORDER BY ID");
$timeins = array();
while($r = mysqli_fetch_assoc($sth)) {
    $timeins[] = $r["timein"];
    //OR
    array_push($timeins, $r['timein']);
}

And then find the distance between the current time and the variable in the array, $timeins[0], and then put the minutes, hours, and days difference in separate simple variables for later use. These variables will be used on their own in if statements to find out if the person has passed certain amounts of time.

edit: the format of the dates being returned from the DB is in the default TIMESTAMP format for MySQL. E.g. 2018-08-06 17:38:37.

  • 写回答

3条回答 默认 最新

  • dsvf46980 2018-08-07 00:33
    关注

    Using the DateTime Class in php is the best way to get accurate results.

    $dateNow = new DateTime('now');
    $dateIn = DateTime::createFromFormat('d-m-Y H:i:s',  $timeins[0]);
    
    $interval = $dateNow->diff($dateIn);
    
    echo $interval->format('%d days, %h hours, %i minutes, %s seconds');
    $deltaDays = $interval->d;
    $deltaHours = $interval->h;
    ...
    

    You have to make sure the input format for you DB date is correct, in this case, I assumed d-m-y H:i:s, and then you can output in any format you need as well, as shown in the date docs: http://php.net/manual/en/function.date.php

    评论

报告相同问题?