Home > Back-end >  Date_sub() on a date array
Date_sub() on a date array

Time:05-30

I am trying to remove exactly 1 year from every date of an array.

Here is the original $periods array

Array ( [0] => 2020-06-01 [1] => 2020-07-01 [2] => 2020-08-01 [3] => 2020-09-01 [4] => 2021-01-01 [5] => 2022-01-01 [6] => 2022-06-01 [7] => 2022-08-01 [8] => 2022-10-01 [9] => 2023-04-01 )

I tried

foreach ($periods as $p) {
date_sub($p,date_interval_create_from_date_string("1 year"));
echo date_format($p,"Y-m-d"). '<br>';
} 

It doesn't return anything... Any pointers would be appreciated.

CodePudding user response:

First set your array values datatype to string => "2020-06-01" , and try this code:

foreach ($periods as $period) {
// convert date string to date model object
$periodDate = date_create($period); 
// subtract date string from coverted date string
date_sub($periodDate,date_interval_create_from_date_string("1 year"));
// covert subtracted date object to readable date fromat
echo date_format($periodDate,"Y-m-d");
} 

CodePudding user response:

You can transform dates using next code:

$res = array_map(
    // convert source string to time, subtract 1 year interval
    // and convert to 'Y-m-d' format in singe function

    fn($p) => date('Y-m-d', strtotime("-1 year", strtotime($p))),
    $periods
);

run PHP online

  •  Tags:  
  • php
  • Related