1

I'm trying to figure out how I can remove the Day and Month from this variable as it's looped. I've tried several strtotime() functions but I can't get the syntax quite right.

foreach ( $results as $result) {
   echo $result->date . "<br />";
}

Shows dates like this:

2014-09-03
2013-09-09
2011-06-01

How can I reassign the variable $result->date so that it only shows the Year like this:

2014
2013
2011
BradM
  • 626
  • 7
  • 17

3 Answers3

1

Easy way is just to explode date string using '-' delimiter and take year element:

foreach ( $results as $result) {
   $dateArr = explode('-', $result->date);
   echo $dateArr[0] . "<br />";
}

More complicated way is to convert sting to UNIX timestamp using strtotime function and then reformat it with date function.

zavg
  • 9,385
  • 4
  • 43
  • 65
1

Just use substr:

$date = '2014-09-18';
echo substr($date, 0, 4);   // Outputs 2014
Phil Cross
  • 8,619
  • 11
  • 45
  • 79
0

this can solve your problem

foreach ( $results as $result) {
   $dateParams = explode("-",$result->data);
   $result->date = $dateParams[0];
   echo $result->date."<br />";
}
ReZa
  • 347
  • 2
  • 17