psy Posted February 2, 2021 Posted February 2, 2021 This is driving me nuts! What I want to do is get 'today' with a name, eg 'Tue', then create an array of week day names going backwards for a week, eg "Tue Mon Sun Sat Fri Thu Wed". My code is where $today is a timestamp for 'today': private static function _onlineWeek ($today, $progams) { $dt = wire('datetime'); $result = []; $dayNames = []; for ($i = 0; $i <= 6; $i++) { $daySeconds = $i * 86400; $dayTS = $today - ($daySeconds); $day = $dt->date('D', $dayTS); $dayNames[] = $day; } $result['labels'] = $dayNames; return $result; } The result is as follows starting with "Thu"???? array(1) { ["labels"]=> array(7) { [0]=> string(3) "Thu" [1]=> string(3) "Wed" [2]=> string(3) "Tue" [3]=> string(3) "Mon" [4]=> string(3) "Sun" [5]=> string(3) "Sat" [6]=> string(3) "Fri" } } Php dates are always a nightmare for me and this just doesn't compute in my brain. What am I doing wrong and suggestions on how to fix gratefully appreciated. Thanks in advance psy
Rudy Posted February 2, 2021 Posted February 2, 2021 @psy You're almost there. The reason why it always starts with Thursday is because when PHP failed to initiate a date, it defaults to Jan 1, 1970, which falls on Thursday. Here is the working code $today = time(); $dayNames = []; for ($i = 0; $i <= 6; $i++) { $daySeconds = $i * 86400; $dayTS = $today - $daySeconds; $day = date('D', $dayTS); $dayNames[] = $day; } var_dump($dayNames); Output: array(7) { [0]=> string(3) "Tue" [1]=> string(3) "Mon" [2]=> string(3) "Sun" [3]=> string(3) "Sat" [4]=> string(3) "Fri" [5]=> string(3) "Thu" [6]=> string(3) "Wed" } 2
Craig Posted February 2, 2021 Posted February 2, 2021 Hi! I'd recommend doing it this way, using a single PHP DateTime object: <?php $date = new DateTime(); $days = []; while (count($days) < 7) { $days[] = $date->format('D'); $date->modify('-1 day'); } print_r($days); /* Array ( [0] => Tue [1] => Mon [2] => Sun [3] => Sat [4] => Fri [5] => Thu [6] => Wed ) */ 9
Recommended Posts