dakim236
dakim236

Reputation: 75

Date format M-Y

I'm trying to find the 12 latest date in the format 'M-Y' using format('M-Y') but I got an error like:

class: "Symfony\Component\Debug\Exception\FatalThrowableError"
message: "Call to a member function format() on string"

I already try:

$date = new DateTime();
$mois = $date->format('M-Y');
$mois1 = $date->format('Y-m-d');
array_push($format1, $mois);
array_push($format2, $mois1);

The result is not that I expect. I get Jun-2019 12 times.

My code is this:

public function getMonthLibelleByDates($filtre) {
        $format1 = []; $format2 = [];
        $month = time();
        for ($i = 1; $i <= 12; $i++) {
            $month = strtotime('last month', $month);
            $months[] = date("r", $month);
        }
        foreach($months as $mois) {
            array_push($format1, $mois->format('M-Y'));
            array_push($format2, $mois->format('Y-m-d'));
        }
        $response = array(
            'format1'=> $format1,
            'format2' =>  $format2      
        );
        return $response;  
    }

I expect the outpout to be the latest 12 months counting from the current date.

Upvotes: 1

Views: 75

Answers (2)

kiske
kiske

Reputation: 430

There's a simplest way to achieve this...

var_dump(getMonthLibelleByDates());

function getMonthLibelleByDates() {
    $res = [
        'format1' => [],
        'format2' => []
    ];
    $timestampBuffer = NULL;

    for ($i = 1; $i <= 12; $i++) {
        $timestampBuffer = strtotime("-$i month");

        $res['format1'][] = date('M-Y', $timestampBuffer);
        $res['format2'][] = date('Y-m-d', $timestampBuffer);
    }

    return $res;
}

Prints...

array(2) {
    ["format1"]=>
  array(12) {
        [0]=>
    string(8) "May-2019"
        [1]=>
    string(8) "Apr-2019"

    //... (too long)

        [10]=>
    string(8) "Jul-2018"
        [11]=>
    string(8) "Jun-2018"
  }
  ["format2"]=>
  array(12) {
        [0]=>
    string(10) "2019-05-26"
        [1]=>
    string(10) "2019-04-26"

    //... (too long)

        [10]=>
    string(10) "2018-07-26"
        [11]=>
    string(10) "2018-06-26"
  }
}

Upvotes: 1

Qirel
Qirel

Reputation: 26490

You appear to be mixing timestamps, date() strings and DateTime objects.

What you can do is create a DateTime object from today, then in a 12-iteration loop modify it to subtract one month. Add the formats in each iteration, then return the response.

public function getMonthLibelleByDates($filtre) {
    $format1 = []; 
    $format2 = [];
    $date = new DateTime();

    for ($i = 1; $i <= 12; $i++) {
        $format1[] = $date->format("M-Y");
        $format2[] = $date->format("Y-m-d");
        $date->modify("-1 month");
    }

    return array(
        'format1'=> $format1,
        'format2' =>  $format2      
    );
}

As a sidenote, it seems that the argument $filtre is not used, so it might be removed?

Upvotes: 1

Related Questions