Nicholas J Panella
Nicholas J Panella

Reputation: 109

php date() and expiration date()

I am creating an application in PHP that will allow the user to create a 'post' that initially lasts for 7 days and the user can add increments of 7 days at any time. I ran into a snag in working with the php date('Y-m-d H:i:s') function and adding days to an already established start date that is pulled from the datebase after the 'post' has been initiated...

$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";

That is what I have so far and it's not doing very much for me. Could anyone show me an example of the right way to do this?

Upvotes: 3

Views: 22158

Answers (2)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146460

One possible way:

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

You can format $diff to your liking. Since you appear to need days:

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

(demo)

For older versions, the syntax is slightly more convoluted:

/* 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);

(demo)

Upvotes: 2

user3520734
user3520734

Reputation:

You almost had it, you forgot to convert the $timestamp to a timestamp before adding the 7 days.

$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";

Upvotes: 4

Related Questions