Drupal - Programmatically set date fields in Drupal 7: Date, Date (ISO Format) and Date (Unix Timestamp)

Here is a code that treat site timezone right for me:

 $node->field_date[LANGUAGE_NONE][0] = array(
    'value' => format_date(strtotime('now'), 'custom', 'Y-m-d H:i:s', 'UTC'),
    'timezone' => 'UTC',  
    'timezone_db' => 'UTC',
  );

Each date field-type is expecting a differently formatted timestamp (based on how it's stored in the DataBase):

// For datetime
$node->field_datetest[$node->language][0]['value'] = "2011-05-25 10:35:58";

// For date
$node->field_datetest[$node->language][0]['value'] = "2011-05-25T10:35:58";

// For datestamp
$node->field_datetest[$node->language][0]['value'] = strtotime("2011-05-25 10:35:58");

Note that you don't need to specify a complete date; for datetime and date you can just pad with zeros, e.g. "2011-05-00 00:00:00" (datetime), "2011-00-00T00:00:00" (date), etc. For datestamp you could just do e.g. strtotime("2011-05-25").

Important: Also note that while the exact value you specify will be stored in the database, the actual time displayed on the site might be different depending on timezone settings. When you create a new datetime/date/datestamp field, you get to choose between five different timezone handling methods. The default one is "site's time zone":

When entering data into the field, the data entered is assumed to be in the site's time zone. When the data is saved to the database, it is converted to UTC. However, if you set a date field programmatically like in the above example then no conversion takes place, so make sure you account for the field's timezone settings. Or in other words, if you use "site's time zone", make sure the time is in UTC.

This information was referenced from the section labeled Date field (datetime, date, datestamp) on fooninja's blog.

This is also a great general resource for programmatic node creation in Drupal 7.


This worked for me.

$node->field_date[LANGUAGE_NONE][0] = array(
      'value' => date('Y-m-d H:i:s', strtotime('now')),
      'timezone' => 'UTC',
      'timezone_db' => 'UTC',
);

Tags:

Datetime

7