php - 如何在Drupal 8中使用日期查询实体

标签 php drupal drupal-8

我希望能够在我们的条件下使用date字段在drupal 8中运行一些实体查询
听是我的密码:

$now = new DrupalDateTime('now');
$query = \Drupal::entityQuery('node');
$query->condition('field_date', $now->format(DATETIME_DATETIME_STORAGE_FORMAT), '>=');
$results = $query->execute();

最佳答案

要解决此问题,我们需要在运行查询之前将时区设置为UTC。

$now = new DrupalDateTime('now');
$now->setTimezone(new \DateTimeZone(DATETIME_STORAGE_TIMEZONE));

然后在查询中使用$now。
我更喜欢直接使用\datetime,然后将其包装到drupal包装器中,因为我可以让ide突出显示所有本机方法。所以我们可以这样做:
$timezone = drupal_get_user_timezone();
    // drupal_get_user_timezone() returns for us the string representation of
    // the timezone the current user has selected,or if they haven't,
    // the site default timezone*/
$start = new \DateTime('now', new \DateTimezone($timezone));
$start->setTime(16,0);
$start->setTimezone(new \DateTimeZone(DATETIME_STORAGE_TIMEZONE));
$start = DrupalDateTime::createFromDateTime($start);
 
$end = new \DateTime('now', new \DateTimezone($timezone));
$end->setTime(18, 0);
$end->setTimezone(new \DateTimeZone(DATETIME_STORAGE_TIMEZONE));
$end = DrupalDateTime::createFromDateTime($end);
 
$query = \Drupal::entityQuery('node');
$query
  ->condition('field_date', $start->format(DATETIME_DATETIME_STORAGE_FORMAT), '>=')
  ->condition('field_date', $end->format(DATETIME_DATETIME_STORAGE_FORMAT), '<=');
$results = $query->execute();

关于php - 如何在Drupal 8中使用日期查询实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57771847/

相关文章:

PHP 将粗体文本移动到数组键

android - 无法通过 webbrowser 从 drupal 站点下载 .apk

paypal - 使用 JavaScript 提交 PayPal 按钮时出现间歇性 500 错误

PHP 性能,从文件读取还是读取数据库?

php - 在回显字符串中插入一个变量

drupal 7在自定义模块中提交表单后查询数据库并显示结果

php - PDO异常 : SQLSTATE[HY000]: General error: 3 Error writing file '/tmp/MYHKgYpv' (Errcode: 28)

php - Drupal 8.8.5 上奇怪的文件/文件夹权限错误

drupal - 访问 $form_state 并从中获取数据

php - MySQL 未返回正确的井号