决定哪一周选择哪一天



我正在努力完成以下任务。我正在开发一个具有三种视图(天、周和月)的自定义日历,可能已经有了一些内容,但我也在重写它,作为我学习工具的一部分。

所以当用户第一次访问时,他们将面对Day视图,当然,箭头可以往返于第二天或前一天。如果他们点击"周视图",它将为他们提供一个7天的概览,默认日期为今天,他们可以再次返回到下周或前一周。最后一个视图是完整的月历,一旦他们点击日期,它将为他们提供当天的详细信息,同时将默认日期重置为他们选择的日期。因此,如果他们返回到周视图,他们将看到周的详细信息,其中包含他们选择的日期。这就是我难以理解的地方,我知道有一些PHP函数可以决定一周中的哪一天,但我似乎无法思考如何输入日期,并从周日开始计算一周的时间。例如,如果我在2012年12月10日通过,我想在2012年7月10日至12月13日开始一周。

衷心感谢您的帮助或指引正确的方向。请原谅我的语法/拼写错误。

  1. 假设$selection将用户选择的日期表示为整数时间戳,date('N', $selection)将返回一个数字代表他们选择的一周中的哪一天(例如星期一=1到周日=7)。

    此结果还表示自所选择的一周(前一个星期日)-$offset。当然,如果您从所选用户的字符串表示开始日期(如您的问题所述,2012年12月10日),您首先需要将日期转换为整数时间戳。

    $selection = strtotime($selection); //if $selection is in string format
    $offset = date('N', $selection);
    


  2. 现在您可以使用$offset来确定周(上周日)-$weekstart

    $weekstart = strtotime("$selection -$offset day");
    


  3. 一旦你有了本周的开始,本周的结束($weekend)当然是6天后,但要计算一下日期,首先需要从整数转换$weekstart时间戳转换为日期的字符串表示形式。您还需要将结果($weekend)转换为日期的字符串表示形式。

    $weekstart = stringftime("%m/%d/%Y", $weekstart); //date format = 10/07/2012
    $weekend = strtotime("$weekstart +6 day");
    $weekend = stringftime("%m/%d/%Y", $weekend);
    



因此:

$selection = "10/12/2012";
$selection = strtotime($selection);
$offset = date('N', $selection);
$weekstart = strtotime("$selection -$offset day");
$weekstart = stringftime("%m/%d/%Y", $weekstart);
$weekend = strtotime("$weekstart +6 day");
$weekend = stringftime("%m/%d/%Y", $weekend);
$output = "Selected Date = $selection n Selected Week = $weekstart - $weekend";
echo $output;

结果在:

Selected Date = 10/12/2012
Selected Week = 10/07/2012 - 10/13/2020



参见:

http://php.net/manual/en/function.date.php
http://php.net/manual/en/function.strtotime.php
http://php.net/manual/en/function.strftime.php

strtotime()函数与date()函数结合用于此任务

例如,2012-10-09之前的1天是

echo date('Y-m-d', strtotime("2012-10-09 -1 day"));

基于智慧的答案,您可以通过几个步骤找到一周中的第一天。查看PHP date()手册了解更多选项,但我相信以下代码会起作用:

// figure out how many days back you have to go, to get to Sunday
$d = date('N', strtotime($mydate));
// figure out Sunday's date
$beginning_of_week = date('Y-m-d', strtotime($mydate." -{$d} days"));
$end_of_week = date('Y-m-d', strtotime($beginning_of_week." +1 week"));
echo "The week {$beginning_of_week} to {$end_of_week}! ";

试试这个函数(来源:Marty Wallace)。

您感兴趣的日期是$date(YYYY-MM-DD格式)和$rollover(全天格式)(例如星期五)。

function getWeeks($date, $rollover)
{
$cut = substr($date, 0, 8);
$daylen = 86400;
$timestamp = strtotime($date);
$first = strtotime($cut . "00");
$elapsed = ($timestamp - $first) / $daylen;
$i = 1;
$weeks = 1;
for($i; $i<=$elapsed; $i++)
{
$dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i);
$daytimestamp = strtotime($dayfind);
$day = strtolower(date("l", $daytimestamp));
if($day == strtolower($rollover))  $weeks ++;
}
return $weeks;
}

最新更新