PHP日期+天

时间:2018-12-20 19:55:40

标签: php date diff mybb

我在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 /stackoverflow.php on line 42

1 个答案:

答案 0 :(得分:1)

您的主要问题是您混淆了两个对象。特别是DateIntervalDateTime。格式化是一件事。

<?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');

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