Drupal 7 – Set a date fieldCondition in EntityFieldQuery

We can select nodes by conditions using EntityFieldQuery.
Drupal 7 – Get specific nodes using EntityFieldQuery

After I have installed the Date module, I could create a content type with a date field called field_expiry_date. When i setup this field, there are 3 date options in the field type.

  • Date
  • Date (ISO format)
  • Date (Unix timestamp)



 

Usually i pick the 1st option and i use the following piece of code to select the nodes which have the expiry date <= today.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', '<node type>')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_expiry_date', 'value', '2012-05-08 00:00:00', '<=');
$result = $query->execute();

 

It also works even you used timestamp in the fieldCondition like REQUEST_TIME.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', '<node type>')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_expiry_date', 'value', REQUEST_TIME, '<=');
$result = $query->execute();

 

If you pick Date (Unix timestamp) when creating the date field. The database will store the date in timestamp format and you can still retrieve the nodes in the same way using the above piece of code.

Done =)

Reference: Drupal Forum – Set date field condition in EntityFieldQuery

2 thoughts on “Drupal 7 – Set a date fieldCondition in EntityFieldQuery”

  1. method#2 with REQUEST_TIME is not working when site’s date time format and date field is set to format d-m-yy format (Indian time format). Is there a way to cast format in fieldcondition?

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.