在选择类型字段中显示上一年

时间:2019-06-13 15:30:59

标签: php symfony date formatting twig

我想在最后一年(每年他都会选择前一年)的年份字段(选择类型字段)中显示

提取我过去使用的最后一年:$year= date("Y")-1;

但是如何将其放入buildForm中:“ Year”也将替换为不显示Year的最后一年

$builder->add('year', ChoiceType::class, array(
'choices'  => array(
    'Year' => '$year=  date("Y")-1)'));

1 个答案:

答案 0 :(得分:0)

我会选择这种内衬:

$oneYearAgo = (new \DateTime('1 year ago'))->format('Y');

或两行相同

$oneYearAgo = new \DateTime('1 year ago');
$oneYearAgo = $oneYearAgo->format('Y');

或其他方法

$dateTime = new \DateTime();
$dateTime->sub(new \DateInterval('P1Y'));
$oneYearAgo = $dateTime->format('Y');

作为一个班轮:

$oneYearAgo = (new \DateTime())->sub(new \DateInterval('P1Y'))->format('Y')

并回答您的问题:

$oneYearAgo = (new \DateTime('1 year ago'))->format('Y');

$builder->add('year', ChoiceType::class, [
    'choices'  => [
        $oneYearAgo => $oneYearAgo,
    ],
]);