Messi Meysam
Messi Meysam

Reputation: 201

Checking time left from a field in database

I've got this filed in database stored as type DATETIME.
Consider the value for it: 2017-12-14 16:17:21

And this is my program logic. I want to check if 72 hours passed else echo you need to wait 48 hours and 22 minutes and 55seconds for example.

$row = $res->fetch_assoc();
$last_dl = $row['last_dl'];

// To seconds from 1970
$last_dl = strtotime($last_dl); //120
$seventy_two_hours_in_seconds = 60 * 60 * 72;

if (time() > ($last_dl + $seventy_two_hours_in_seconds)) {
    echo "72 Passed";
} else {
    echo "You need to wait: " . date('H/h i/m s/s',mktime(0, 0, ($last_dl + $seventy_two_hours_in_seconds) - time()));
}

What is wrong with the logic. Cause it shows way less hours.

Upvotes: 2

Views: 51

Answers (1)

Ivan
Ivan

Reputation: 2579

You can calculate time in second to wait, and after present it in hours, minutes and seconds:

<?php
$row = $res->fetch_assoc();
$last_dl = $row['last_dl'];

// To seconds from 1970
$last_dl = strtotime($last_dl); //120
$seventy_two_hours_in_seconds = 60 * 60 * 72;

if (time() > ($last_dl + $seventy_two_hours_in_seconds)) {
    echo "72 Passed";
} else {
    $wait = date('U', $last_dl + $seventy_two_hours_in_seconds) - date('U'); // seconds for wait
    $hours = floor($wait /3600);
    $min = floor(($wait / 60) % 60);
    $sec = $wait % 60;
    echo "You need to wait: ". $hours. ':'. $min.':'.$sec ."\n";
}

http://sandbox.onlinephpfunctions.com/code/08477cd78c82dfe2b4a5c5f4aee6414866999a8c

Upvotes: 1

Related Questions