How to determine whether a UNIX timestamp occured 'last week'
I have a unix timestamp and I want to be able to test whet开发者_如何学运维her it occurred earlier than 12:00am Sunday of the current week. Any suggestions?
<?php
/**
* @param $t UNIX timestamp
* @return true iff the given time fell in the previous Sunday->Sunday window
*/
function f($t) {
$a = strtotime("last Sunday");
$b = strtotime("-1 week", $a);
return ($b <= $t && $t < $a);
}
var_dump(f(strtotime("2011-08-12 11:00")));
var_dump(f(strtotime("2011-08-08 11:00")));
var_dump(f(strtotime("2011-08-04 11:00")));
var_dump(f(strtotime("2011-08-01 11:00")));
?>
Output:
bool(false)
bool(false)
bool(true)
bool(true)
Live demo.
I think you can generate the timestamp for "12:00am sunday of the current week" using the datetime class: http://www.php.net/manual/en/book.datetime.php
You should be able to generate a date time object for the target date, then use gettimestamp: http://www.php.net/manual/en/datetime.gettimestamp.php to convert it into a timestamp.
You can then compare that timestamp to see if it is less than the timestamp you have generated.
Edit: Some code (although not as elegant as Tomalak Geret'kal's)
<?php
//Get current year and week
$year = date('Y');
$week = date('W');
//Get date
$date = date("Y-m-d", strtotime("$year-W$week-7"));
//Get date with time
$datetime = new DateTime("$date 00:00:00");
//Display the full date and time for a sanity check.
echo $datetime->format('Y-m-d h:i:s') . ' = ';
//Convert to timestamp:
$timestamp = $datetime->getTimeStamp();
echo $timestamp;
//Do your comparison here:
if($yourtimestamp < $timestamp){
return true;
}
精彩评论