How do I set first day of the week to Monday when

2020-04-14 08:54发布

I am using the following code to build a Google Chart, to pull in all of entries in a MySQL table corresponding to the Week Numbers in a year. At the moment the Week Numbers start on a Sunday, and I would like to change this so that they start on a Monday, but I'm not sure how to do this.

$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++;
    }

REVISED CODE

$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条回答
够拽才男人
2楼-- · 2020-04-14 09:49
WEEK(date[mode]); 

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

The default arugment is 0 which is sunday, setting this to 1 will be monday, 2 tuesday and so on.

week(date,1);
查看更多
beautiful°
3楼-- · 2020-04-14 09:59

For it to work in your code, you should be able to change the query to:

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

However, I think I could go one step further and use the GROUP BY to make one sql call, and then iterate over the results;

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

Alternatively, you might need to use WEEK(Date,2) depending on how you want to handle weeks that span between years.

查看更多
登录 后发表回答