【问题标题】:Display the last year in a choice type field在选择类型字段中显示上一年
【发布时间】:2019-06-13 15:30:59
【问题描述】:

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

提取去年我习惯用的:$year= date("Y")-1;

但是我怎样才能把它放在 buildForm 中:'Year' 也将被替换为不显示单词 year 的最后一年

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

【问题讨论】:

    标签: php symfony date formatting twig


    【解决方案1】:

    我会选择这个oneliner:

    $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,
        ],
    ]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 2021-11-15
      • 2012-07-23
      • 2022-10-13
      • 2021-12-19
      相关资源
      最近更新 更多