0

I have array of week numbers from 1 to 52. how i can convert it to

[week 1 jan],[week 2 jan] .......

using PHP

Man Mann
  • 423
  • 2
  • 10
  • 17

2 Answers2

0

Try a loop, start with 1/jan, use DateInterval::createFromDateString('1 week'); and DateTime::add each time in the loop to add the next week, use DateTime::format to get the month also checking the current year in each iteration to make sure the loop hasn't moved to the next year.

Code:

date_default_timezone_set("UTC");
$weeks = array();
$dt = new DateTime("2013-01-01");
$interval = DateInterval::createFromDateString("1 week");

for($i=1; $i <= 52; $i++)
{
    $weeks[$i] = "week " . $i . " " . $dt->format("M"); 
    $dt = $dt->add($interval);
}

print_r($weeks);

If you want a function that will return a month abbreviation from a week:

function weekMonth($week)
{
    date_default_timezone_set("UTC");
    return (new DateTime("2013-01-01"))->add(DateInterval::createFromDateString($week." week"))->format("M");
}

echo weekMonth(6);
Neaox
  • 1,933
  • 3
  • 18
  • 29
0

OK ... I fix it and here is my code

function getWeeks($date, $rollover)
{
    $cut = substr($date, 0, 8);
    $daylen = 86400;

    $timestamp = strtotime($date);
    $first = strtotime($cut . "00");
    $elapsed = ($timestamp - $first) / $daylen;

    $i = 1;
    $weeks = 1;

    for($i; $i<=$elapsed; $i++)
    {
        $dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i);
        $daytimestamp = strtotime($dayfind);

        $day = strtolower(date("l", $daytimestamp));

        if($day == strtolower($rollover))  $weeks ++;
    }

    return $weeks;
}

and in the foreach I added

$x="1/1/2013 + ".$record->tms." weeks";
$m=date("Y-m-d", strtotime($x));
$first_week_start=getWeeks($m, "sunday");
if($first_week_start == 1){$typo="st";}
if($first_week_start == 2){$typo="nd";}
if($first_week_start == 3){$typo="rd";}
if($first_week_start == 4){$typo="th";}
if($first_week_start == 5){$typo="th";}
$month=date("M", strtotime($m));
$final_format .= "'".$first_week_start.$typo ." week in ".$month."'";
Man Mann
  • 423
  • 2
  • 10
  • 17