0

我有从 1 到 52 的周数数组。我如何将其转换为

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

使用 PHP

4

2 回答 2

0

尝试一个循环,从 开始1/jan,每次在循环中使用DateInterval::createFromDateString('1 week');DateTime::add添加下周,使用DateTime::format获取月份也在每次迭代中检查当前年份,以确保循环没有移动到下一年。

代码:

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);

如果您想要一个从一周返回一个月缩写的函数:

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

echo weekMonth(6);
于 2013-09-09T02:15:33.267 回答
0

好的......我修复它,这是我的代码

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;
}

在我添加的 foreach

$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."'";
于 2013-09-09T03:01:42.343 回答