Jump to content
Sign in to follow this  
psy

Get names of the week backwards from today

Recommended Posts

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"]=&gt;
  array(7) {
    [0]=&gt;
    string(3) "Thu"
    [1]=&gt;
    string(3) "Wed"
    [2]=&gt;
    string(3) "Tue"
    [3]=&gt;
    string(3) "Mon"
    [4]=&gt;
    string(3) "Sun"
    [5]=&gt;
    string(3) "Sat"
    [6]=&gt;
    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

 

Share this post


Link to post
Share on other sites

@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" } 

 

  • Like 2

Share this post


Link to post
Share on other sites

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
)
*/

 

  • Like 9

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...