totalnoob
totalnoob

Reputation: 2741

php getting seasons programmatically

I have a database with historic data and I'd like to sort them out by seasons via dates

eg. if season 1 began on 2014-01-01 - 2014-04-30, season 2 on 2014-05-01 - 2014-08-31, season 3 on 2014-09-01 - 2014-12-31, seasons 4, 5 and 6 would be 2015-01-01 - 2015-04-30, 2015-05-01 - 2015-08-31, and 2015-09-01 - 2015-12-31.

It's really only upping the year starting from 2014.

I'd want to do something as simple as using a query string of $_GET['season'] to get season=2 and programmatically know to look for 2014-05-01 - 2014-08-31 based on a start year.

what's the best way to do this?

so far I have this code

 <?
      $season = $_GET['season'];

      $endmonth = $season * 4;
      $startmonth = $endmonth - 4;
      echo "startmonth: " . $startmonth . "<br />";
      echo date("Y-m-d H:i:s", strtotime("+" . $startmonth . " months", strtotime('2005-01-01 00:00:00'))) . "<br />";
      echo date("Y-m-d H:i:s", strtotime("+" . $endmonth . " months", strtotime('2005-01-01 00:00:00'))) . "<br />";
 ?>

I need it to be exact on the dates

Upvotes: 1

Views: 480

Answers (1)

Stefan
Stefan

Reputation: 1258

From a 'season number' to the season you could use a modulo calculation: $season = $theseasonnumber % 4

If you want to know the date range of a season, then the start month would be ending on $endmonth = $season * 3 and starting on $startmonth = $endmonth - 2

From there is just some logic and playing with the date functions from PHP.

edit based on edited question I made you a working example function

<?php

function season_to_dates($season, $startyear = 2014)
{
    $year = floor($season / 4); // this are years on top of the startyear

    $actual_season = $season % 4; // returns the actual season
    if($actual_season == 0) $actual_season = 4; // little trick

    $endmonth = $actual_season * 3; 
    $startmonth = $endmonth - 2; 

    return array(
        'season' => $actual_season,
        'start' => date("Y-m-d", mktime(0,0,0,$startmonth,1,$year+$startyear)),
        'end'   => date("Y-m-t", mktime(0,0,0,$endmonth,1,$year+$startyear))
    );
}


if(!isset($_GET['season'])) $season = rand(1,40);
else $season = $_GET['season'];

echo 'Result for season ' . $season . '<pre>';
print_r(season_to_dates($season));
echo '</pre>';


?>

Upvotes: 1

Related Questions