Reputation: 9992
I'm Getting Saved Date/Time from Database in Following Format,
$date_time = date("j M, Y, g:i a"); //1 Feb, 2015, 12:00 am
Looking for a solution to add 7 days in $date_time to create expiry date, Tried several solutions discused on stackoverflow but none of them is working for me,
Any help will be appriciated. Thanks
Edited
@panther answered partially worked with only Date
$date_time = date("j M, Y");
but with Date/Time
$date_time = date("j M, Y, g:i a");
adding 7 days
$end_date = date("j M, Y, g:i a", strtotime($date_time . ' + 7 days'));
will return the result "31 Dec, 1969, 12:00 am"
So I tried with only Date to calcualte the difference (Inside PHP While Loop)
<?php if ($end_date>$date_time) { ?>
Expired
<?php } else { ?>
Active
<?php } ?>
And it didn't work, either it sets all records to Active or Expired,
So I'm Back to Sqaure 1.
Note: I tried with UNIX_TIMESTAMP but the end result same, either sets all records to Active or Expired.
Upvotes: 0
Views: 1035
Reputation: 1722
You could try using PHPs DateTime Object to get the current Time
$date_time_obj = new \DateTime();
$date_time = $date_time->format('j M, Y, g:i a');
And then use the add() method to get your expiry time
$end_date_obj = clone $date_time_obj;
$end_date_obj = $end_date_obj->add(new \DateTimeInterval('P7D'));
$end_date = $end_date_obj->format('j M, Y, g:i a');
A little more complicated than the other answers, i know :) But maybe also a little more helpfull in the future!
Cheers
Upvotes: 0
Reputation: 454
Using DateTime is also a good option:
$date_str = "..."; // from database
$date_format = "j M, Y, g:i a";
$expire_date = DateTime::createFromFormat($date_format, $date_str);
$expire_date = $expire_date->add(DateInterval::createFromDateString('+7 days'));
and if you need it formated back to string:
$expire_date->format($date_format);
Upvotes: 0
Reputation: 27072
Try this:
$date_time = date("j M, Y, g:i a");
$end_date = date("j M, Y, g:i a", strtotime($date_time . ' + 7 days'));
Upvotes: 4