PHP日期+天数

PHP Date + days

我在 MyBB 中得到了类似的东西,我想添加 5 天到现在($datetime1),其中一个应该存储在 $nowPlus5D 中。 此外,在 $leeft 变量中显示剩余的天数、小时数、分钟数。 (购买天数 + 5 天)- datenow 之间的差异

define("IN_MYBB", 1);
require_once "global.php";


$data_zakupu = $db->query("
    SELECT timestamp
    FROM ".TABLE_PREFIX."subs
    WHERE txn_id <> '' AND uid=".$mybb->user['uid']." ORDER BY lid DESC          LIMIT 1;
");


     $dat = $db->fetch_field($data_zakupu,"timestamp");
     $date_buy = date('d-m-Y H:i:s', $dat); // added h:i:s

    // Total bought
    echo '<br><hr>';
   echo 'Bought date - ' . $date_buy;
  echo '<br>';

 $datetime2 = new DateTime('now');
  $datetime1 = new DateTime($date_buy); 

 $interval = $datetime1->diff($datetime2);

  $nowPlus5D = $datetime1->add(new DateInterval('P5D'));
 echo '<hr><br>';
 echo 'Expiration date - ' . $nowPlus5D->format('%a days, %h hours, %i, minutes');
 echo '<br>';

 $leeft = $nowPlus5D->diff($datetime1);
 var_dump($leeft);
 echo '<br>';
 echo $left->format('%a days, %h hours, %i, minutes');

我明白了

Bought date - 20-12-2018 18:20:48

Expiration date - %pm 25pm1848, %06 062018000000Tue, 25 Dec 2018 18:20:48 +010048, %20, 12201200000031Europe/Warsaw48
  object(DateInterval)#14 (15) { ["y"]=> int(0) ["m"]=> int(0) ["d"]=> int(0) ["h"]=> int(0) ["i"]=> int(0) ["s"]=> int(0) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(0) ["days"]=> int(0) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) }

Fatal error: Call to a member function format() on integer in /Whosebug.php on line 42

您的主要问题是混淆了几个对象。具体来说 DateInterval with DateTime。格式是一回事。

<?php
$date_buy = '2018-12-15 10:05:22';

$datetime2 = new DateTime('now');
$datetime1 = new DateTime($date_buy); 

$interval = $datetime1->diff($datetime2);    
$nowPlus5D = $datetime1->add(new DateInterval('P5D'));

//THIS IS A DATETIME OBJECT, NOT AN INTERVAL! NOTE FORMAT `Y-m-d H:i:s`
echo 'Expiration date - ' . $nowPlus5D->format('d \d\a\y\s, H \h\o\u\r\s, i \m\i\n\u\t\e\s');



var_dump($nowPlus5D);
var_dump($datetime1);
// ^ Notice those are the same? A result of `$nowPlus5D = $datetime1->add(new DateInterval('P5D'));`

// and Intervals then are of course zeros...
$left = $nowPlus5D->diff($datetime1);
echo '<br>';
echo $left->format('%a days, %h hours, %i, minutes');

// could do this...
$left = $nowPlus5D->diff(new \DateTime);
echo $left->format('%a days, %h hours, %i, minutes');

无论如何,认为您的主要困惑在于这两种对象类型。想象一下,你可以从这里拿走它。