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
  • 646
  • 8
  • 18

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
  • 10,351
  • 4
  • 44
  • 67
1

Just use substr:

$date = '2014-09-18';
echo substr($date, 0, 4);   // Outputs 2014
Phil Cross
  • 9,017
  • 12
  • 50
  • 84
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