我希望能够在我们的条件下使用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/