简体   繁体   中英

How long time it is left? php + date

//Example data
$current_time = 1318075950;
$unbanned_time = $current_time + strtotime('+1 minute');


if ($unbanned_time > $current_time) {
  $th1is = date('Y-m-d H:i:s', $unbanned_time) - date('Y-m-d H:i:s', $current_time);
   echo date('Y-m-d H:i:s', $th1is);

I am trying to output how long time it is until the user is unbanned... year months, days, hours, minutes and seconds... But this is giving me some weird results..

You should check manual on how to work with date/time functions.

First of all, instead of

$current_time + strtotime('+1 minute')

use

strtotime('+1 minute', $current_time);

(see manual on strtotime ).

Secondly, date function returns a string. Subtracting two strings is not really useful in most cases.

if ($unbanned_time > $current_time) {
  $th1is = $unbanned_time - $current_time;
  echo $th1is/3600 . ' hours';
}

This will output the remaining time in hours but there are many functions available that will produce better formatting (or you can code one for yourself).

I would recommend to use DateTime

$DateTime = new DateTime();
$unbanned_DateTime = new DateTime();
$unbanned_DateTime = $unbanned_DateTime->modify('+1 minute');

if ( $unbanned_DateTime > $DateTime ) {
    $interval = $DateTime->diff($unbanned_DateTime);
    $years = $interval->format('%y'); 
    $months = $interval->format('%m'); 
    $days = $interval->format('%d'); 
    $hours = $interval->format('%h'); 
    $minutes = $interval->format('%i'); 
    $seconds = $interval->format('%s');
}

Instead of using every single value as variable you can use ->format() for one output. As you like.

Remember DateTime->format() needs a timezone setting up in your php.ini or with

date_default_timezone_set('....');

date() returns a string, substracting two strings makes no sense here. You can use basic maths to calculate the remaining time:

<?php
$current_time = time();
$unbanned_time = /* whatever */;
$seconds_diff = $unbanned_time - $current_time();
echo "You're unbanned at " . date("Y-m-d H:i:s", $unbanned_time) . " which is over ";
if ($seconds_diff <= 120) {
    echo "$seconds_diff seconds";
} else if ($seconds_diff <= 7200) {
    echo floor($seconds_diff / 60) . " minutes";
} else if ($seconds_diff <= 7200 * 24) {
    echo floor($seconds_diff / 3600) . " hours";
} else {
    echo floor($seconds_diff / 3600 / 24) . " days";
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM