Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of all months and year between two dates in PHP

Tags:

date

php

mysql

I am trying to explain the details so that this is easy to understand.

I want a list of month and year based on the difference of month and year.

I am implementing search functionality based on start month with year and end month with year. So!

start Selection - 01(month)-2009 (Yr)

End selection 10(month)-2009 (Yr)

What I want from MySQL is:

Month                        Year
JAN                          2009
FEB                          2009
MAR                          2009
APR                          2009
MAY                          2009
JUN                          2009
JUL                          2009
AUG                          2009
SEP                          2009
OCT                          2009
like image 542
santosh Avatar asked Nov 28 '22 15:11

santosh


1 Answers

FractalizeR answer is the right one.

Just let me expand by defining the functions:

function GetMonthsFromDate($myDate) {
  $year = (int) date('Y',$myDate);
  $months = (int) date('m', $myDate);
  $dateAsMonths = 12*$year + $months;
  return $dateAsMonths;
}

function GetDateFromMonths($months) {
  $years = (int) $months / 12;
  $month = (int) $months % 12;
  $myDate = strtotime("$years/$month/01"); //makes a date like 2009/12/01
  return $myDate;
}

PS: tried to post as a comment but the formating got screwed. (Of course this functions could be rewritten as one liners but wanted to be more readable)

like image 108
elviejo79 Avatar answered Dec 07 '22 23:12

elviejo79