在PHP中计算最后结束的一周

时间:2012-09-05 11:56:41

标签: php mysql

我正在使用时间戳对数据库进行查询。现在我正在使用硬编码日期进行查询,

$dd1 = 20;//date("d",$ddb1);
    $mm1 = date("m");
    $yyyy1 = date("Y");
    $dd2 = 26;//date("d",$ddb2);
    $mm2 = date("m");
    $yyyy2 = date("Y");

但是每当我运行脚本时,我都需要代码来计算上周的数据(周一到周日)。例如,我今天运行了脚本(Wensday),因此计算出的时间应该是从(周一到周日)的最后一周。同样的结果应该是本周的任何其他日子,直到周日晚上的12:00:01。

尝试做类似的事情:

    //$ddb1 = time() - ($argv[1] * 24 * 60 * 60);
    //$ddb2 = time() - ($argv[2] * 24 * 60 * 60); 

要从当前日期开始减去天数,但必须有自动方式来执行此操作。

4 个答案:

答案 0 :(得分:3)

$first_day = strtotime('Last Week');
$last_day = strtotime('Last Sunday');

echo "Last Monday was ".date('m-d-Y', $first_day);
echo "Last Sunday was ".date('m-d-Y', $last_day);

#Last Monday was 08-27-2012
#Last Sunday was 09-02-2012

答案 1 :(得分:2)

为什么不使用strtotime

$lastsunday=strtotime("last Sunday");
$lastmonday=strtotime("last Sunday")-(7*86400);

编辑:

<?php
    date_default_timezone_set('Australia/NSW');
    $lastSunday=strtotime("last Sunday");
    $lastMonday=strtotime("last Sunday")-(6*86400);

    echo "Last Sunday was ".date('d-m-Y', $lastSunday)."<br>";
    echo "Last Monday was ".date('d-m-Y', $lastMonday);

?>  

输出:

Last Sunday was 02-09-2012
Last Monday was 27-08-2012 

答案 2 :(得分:1)

获取最后一个星期天:

$last_sunday = strtotime('Last Sunday');

然后减去6天以获得最后一个星期一:

$last_monday = date($last_sunday-86400*6)

答案 3 :(得分:0)

试试这个: -

/**
* int nth_day_of_month(int $nbr, str $day, int $mon, int $year)
*   $nbr = nth weekday to find
*   $day = full name of weekday, e.g. "Saturday"
*   $mon = month 1 - 12
*   $year = year 1970, 2007, etc.
* returns UNIX time
*/

function nth_day_of_month($nbr, $day, $mon, $year)
{
   $date = mktime(0, 0, 0, $mon, 0, $year);
   if($date == 0)
   {
      user_error(__FUNCTION__."(): Invalid month or year", E_USER_WARNING);
      return(FALSE);
   }
   $day = ucfirst(strtolower($day));
   if(!in_array($day, array('Sunday', 'Monday', 'Tuesday', 'Wednesday',
         'Thursday', 'Friday', 'Saturday')))
   {
      user_error(__FUNCTION__."(): Invalid day", E_USER_WARNING);
      return(FALSE);
   }
   for($week = 1; $week <= $nbr; $week++)
   {
      $date = strtotime("next $day", $date);
   }
   return($date);
} 


function getWeekNoByDay($year = 2007,$month = 5,$day = 1) {
    return ceil(($day + date("w",mktime(0,0,0,$month,1,$year)))/7);
}