php日期()和过期日期()


php date() and expiration date()

我正在用PHP创建一个应用程序,该应用程序将允许用户创建一个最初持续7天的"帖子",用户可以随时添加7天的增量。我在使用php日期("Y-m-d H:I:s")函数时遇到了一个障碍,并在"post"启动后从数据库中提取的已经确定的开始日期中添加了天。。。

$timestamp = "2016-04-20 00:37:15";
$start_date = date($timestamp);
$expires = strtotime('+7 days', $timestamp);
//$expires = date($expires);
$date_diff=($expires-strtotime($timestamp)) / 86400;
echo "Start: ".$timestamp."<br>";
echo "Expire: ".$expires."<br>";
echo round($date_diff, 0)." days left";

到目前为止,这就是我所拥有的,对我来说并没有多大帮助。有人能给我举一个正确的例子吗?

您几乎用完了,在添加7天之前忘记将$timestamp转换为时间戳。

$timestamp = "2016-04-20 00:37:15";
$start_date = date($timestamp);
$expires = strtotime('+7 days', strtotime($timestamp));
//$expires = date($expires);
$date_diff=($expires-strtotime($timestamp)) / 86400;
echo "Start: ".$timestamp."<br>";
echo "Expire: ".date('Y-m-d H:i:s', $expires)."<br>";
echo round($date_diff, 0)." days left";

一种可能的方法:

/* PHP/5.5.8 and later */
$start = new DateTimeImmutable('2016-04-20 00:37:15');
$end = $start->modify('+7 days');
$diff = $end->diff($start);

您可以根据自己的喜好格式化$diff。由于你似乎需要几天:

echo $diff->format('%d days');

(演示)

对于旧版本,语法稍微复杂一些:

/* PHP/5.3.0 and later */
$start = new DateTime('2016-04-20 00:37:15');
$end = clone $start;
$end = $end->modify('+7 days');
$diff = $end->diff($start);

(演示)