PHP: Check if it has been one week since timestamp
Let's assume:
$time = '2010-05-17 02:49:30' // (retrieved from MySQL TIMESTAMP field)
How do I do the following in PHP:
1) Check if it has been more than one week since this time has passed?
2) Assuming "fa开发者_Python百科lse" on (1), find out how much more time until the one week mark, rounded to days and hours remaining.
I know this is pretty straightforward, but it uses a very specific syntax. Having never played with time calculations before, I'd appreciate some guidance.
Thanks!
$time = strtotime('2010-05-10 02:49:30');
$one_week_ago = strtotime('-1 week');
if( $time > $one_week_ago ) {
// it's sooner than one week ago
$time_left = $time - $one_week_ago;
$days_left = floor($time_left / 86400); // 86400 = seconds per day
$hours_left = floor(($time_left - $days_left * 86400) / 3600); // 3600 = seconds per hour
echo "Still $days_left day(s), $hours_left hour(s) to go.";
}
Doesn't strtotime let you do things like this...
$timestamp = strtotime($time);
$oneweekago = strtotime("-1 week");
if($oneweekago<=$timestamp) {
// it's been less than one week
$secondsleft = $oneweekago - $timestamp;
// ...
}
You can use strptime/strftime (or mysql TIMESTAMP) to parse your time and then check if it is at least one week form the present (one week = 604800 seconds).
If one week has not passed then you can work out how many seconds still remain from which you can calculate days and hours left.
SELECT * FROM 'contents'
WHERE (WEEK(NOW(), 7) = WEEK('publish_up', 7)) AND YEAR('publish_up') = YEAR(NOW())
There are lots of great functions for date manipulation. Take a look at this page in the manual http://php.net/manual/en/ref.datetime.php
mysql has a bunch of datetime functions. date_add and datediff among them.
though to count hours could be tricky.
Anyway I can't believe you going to do that comparison using PHP
Here you are:
$time = strtotime('2010-05-9 02:49:30');
$oneWeekAgo = time() - (7 * 84600);
$hasOneWeekPassed = $time < $oneWeekAgo;
if (!$hasOneWeekPassed)
{
$timeLeft = $time - $oneWeekAgo;
}
var_dump($hasOneWeekPassed);
var_dump($timeLeft);
Absolutely do NOT do what Col. Shrapnel said (calculate it in MySQL). Not only is it completely unnecessary but that will be at least 20 times slower than the pure PHP above.
精彩评论