这是我在 drupal 8 模块中所做的,以从 DrupalDateTime 获取格式化日期
我。如果您有一个日期并想要对其进行格式化,只需将其传递给类的静态方法 (DrupalDateTime),如下所示。您可以用您的日期变量替换字符串。
下面显示了使用 DrupalDateTime
的静态版本和非静态版本
$date = DrupalDateTime::createFromFormat('j-M-Y', '20-Jul-2019');
// Using the static method prints out: 20-Jul-2019:11:am
$date = new DrupalDateTime('now'); // grab current dateTime using NON static
$date->format('l, F j, Y - H:i'); // format it
// prints out nicely formatted version: Tue, Jul 16, 2019 - 11:34:am
// you can remove H:i and what's after it if you don't want hours or am pm
$date = new DrupalDateTime('now'); // grab current dateTime
// Or print $date->format('d-m-Y: H:i A');
// prints out: 16-07-2019: 11:43 AM
更多示例:
$date = new DrupalDateTime();
$date->setTimezone(new \DateTimeZone('America/Chicago'));
print $date->format('m/d/Y g:i a');
// The above prints current time for given Timezone
// prints : 07/16/2019 10:59 am
// Another variations of the above except it takes specific date and UTC zone
$date = new DrupalDateTime('2019-07-31 11:30:00', 'UTC');
$date->setTimezone(new \DateTimeZone('America/Chicago'));
print $date->format('m/d/Y g:i a');
// prints 07/31/2019 6:30 am
要在您的模块/代码中使用这些,您需要在文件顶部包含以下内容;
use Drupal\Core\Datetime\DrupalDateTime;
另外注意 DrupalDateTime 扩展了 DateTimePlus() 它自己“用更灵活的初始化参数包装 PHP DateTime 类......根据文档......”
如何使用 Drush 进行测试。
将上面的代码保存在一个 php 脚本中,然后让 drush 在它引导 drupal 之后运行 srcipt,如下所示:
drush -r /path-to-your-drupal-documentRoot -l example.com scr ~/path-to your-script
对于多站点,请确保您使用... drush -l http.... 如上所述
注意:
我发布了类似的答案:https://drupal.stackexchange.com/questions/252333/how-to-get-formatted-date-string-from-a-datetimeitem-object/283529#283529