首页 > 解决方案 > PHP中的date_format()不返回格式化的日期

问题描述

date_format函数不返回变量的格式化值,而是仅返回当前日期

我尝试了不同的日期变量和格式,但无济于事。这是在 WordPress 环境中完成的。

……

 <span class="some-css-class">
  <?php
   $eventDate = new DateTime(the_field('date_event'));
   //'event_date is the name of the date time field created for the post
   echo date_format($eventDate,'M'); 
  ?>
  </span>

……

我尝试了不同的变量和数字格式。搜索了 WordPress 环境特定的解决方案,但没有一个有效。结果显示今天的日期被格式化而不是给定日期。

结果以非格式化形式显示事件的日期,以格式化形式显示今天的日期。

标签: phpwordpressdatedatetime

解决方案


结果显示今天的日期被格式化而不是给定日期。

那是因为您没有在这里给 DateTime 构造函数提供任何日期 - 所以它默认为今天。

$eventDate = new DateTime(the_field('date_event'));

the_field 直接输出值。您想将值作为参数传递给 DateTime 构造函数,因此您需要使用返回值的函数而不是直接输出它 - get_field


推荐阅读