在PHP / MySQL中使用Week(Date)时,如何将星期的第一天设置为星期一?

时间:2013-04-24 15:56:07

标签: php mysql date week-number

我正在使用以下代码构建Google图表,以便在一年内提取对应于周数的MySQL表中的所有条目。目前周数从星期日开始,我想改变它,以便它们在星期一开始,但我不知道该怎么做。

$i=1;
    while($i<=53)
       {
        $week_start = new DateTime();
        $week_start->setISODate(2013,$i+1);
        $date_display = $week_start->format('j M Y');

        $sessions = $wpdb->get_var($wpdb->prepare("SELECT Sum(Due) from patient_sessions WHERE Type='Session' AND Week(Date)='$i'"));

        $temp = array();

        $temp[] = array('v' => (string) $date_display); 
        $temp[] = array('v' => (string) $sessions); 
        $rows[] = array('c' => $temp);
        $i++;
    }

修订后的代码

$sessions = $wpdb->get_results($wpdb->prepare("SELECT Due,Date from patient_sessions WHERE Type='Session'"));
$work_times = $wpdb->get_results($wpdb->prepare("SELECT Amount,Date from work_times"));
$expenses = $wpdb->get_results($wpdb->prepare("SELECT Amount,Date from expenses WHERE Client='Psychotherapy'"));

$i=1;
while($i<=53) {
    $week_start = new DateTime();
    $week_start->setISODate(2013,$i+1);
    $date_display = $week_start->format('j M Y');

    $session_total = 0;
    $work_time_total = 0;
    $expense_total = 0;


      foreach ($sessions as $session) {
    if (date("W", strtotime($session->Date)) == $i) {
    $session_total = ($session_total+$session->Due);
    }
    }

         foreach ($work_times as $work_time) {
    if (date("W", strtotime($work_time->Date)) == $i) {
    $work_time_total = ($work_time_total+$work_time->Amount);
    }
    }

          foreach ($expenses as $expense) {
    if (date("W", strtotime($expense->Date)) == $i) {
    $expense_total = ($expense_total+$expense->Amount);
    }
          }

    $balance = ($session_total + $work_time_total - $expense_total);

    $temp = array();

    $temp[] = array('v' => (string) $date_display); 
    $temp[] = array('v' => (string) $balance); 
    $rows[] = array('c' => $temp);
    $i++;
}

2 个答案:

答案 0 :(得分:10)

WEEK(date[mode]); 

date = a date value.    
mode = An integer indicating the starting of the week. 

默认参数为0,这是星期日,将此设置为1将是星期一,2星期二,依此类推。

week(date,1);

答案 1 :(得分:0)

要使其在您的代码中运行,您应该能够将查询更改为:

"SELECT Sum(Due) FROM patient_sessions WHERE Type='Session' AND Week(Date,1)=$i"

但是,我想我可以更进一步,使用GROUP BY进行一次SQL调用,然后迭代结果;

"SELECT Week(Date,1), SUM(DUE) FROM patient_sessions WHERE Type='Session' GROUP BY Week(Date,1)"

或者,您可能需要使用WEEK(日期,2),具体取决于您希望处理几年之间的周数。