diff --git a/core/includes/form.inc b/core/includes/form.inc
index 002de6f..dc6f23b 100644
--- a/core/includes/form.inc
+++ b/core/includes/form.inc
@@ -7,6 +7,7 @@
use Drupal\Core\Utility\Color;
use Drupal\Core\Template\Attribute;
+use Drupal\Core\Datetime\DrupalDateTime;
/**
* @defgroup forms Form builder functions
@@ -1703,8 +1704,8 @@ function form_error(&$element, $message = '') {
* - $element['#process']: An array of functions called after user input has
* been mapped to the element's #value property. These functions can be used
* to dynamically add child elements: for example, for the 'date' element
- * type, one of the functions in this array is form_process_date(), which adds
- * the individual 'year', 'month', 'day', etc. child elements. These functions
+ * type, one of the functions in this array is form_process_datetime(), which adds
+ * the individual 'date', and 'time'. child elements. These functions
* can also be used to set additional properties or implement special logic
* other than adding child elements: for example, for the 'details' element
* type, one of the functions in this array is form_process_details(), which
@@ -2955,117 +2956,29 @@ function password_confirm_validate($element, &$element_state) {
}
/**
- * Returns HTML for a date selection form element.
+ * Returns HTML for an #date form element.
*
- * @param $variables
+ * Supports HTML5 types of 'date', 'datetime', 'datetime-local', and 'time'.
+ * Falls back to a plain textfield. Used as a sub-element by the datetime
+ * element type.
+ *
+ * @param array $variables
* An associative array containing:
* - element: An associative array containing the properties of the element.
* Properties used: #title, #value, #options, #description, #required,
- * #attributes.
+ * #attributes, #id, #name, #type, #min, #max, #step, #value, #size.
*
* @ingroup themeable
*/
function theme_date($variables) {
$element = $variables['element'];
-
- $attributes = array();
- if (isset($element['#id'])) {
- $attributes['id'] = $element['#id'];
- }
- if (!empty($element['#attributes']['class'])) {
- $attributes['class'] = (array) $element['#attributes']['class'];
+ if (empty($element['attribute']['type'])) {
+ $element['attribute']['type'] = 'date';
}
- $attributes['class'][] = 'container-inline';
-
- return '
' . drupal_render_children($element) . '
';
-}
-
-/**
- * Expands a date element into year, month, and day select elements.
- */
-function form_process_date($element) {
- // Default to current date
- if (empty($element['#value'])) {
- $element['#value'] = array(
- 'day' => format_date(REQUEST_TIME, 'custom', 'j'),
- 'month' => format_date(REQUEST_TIME, 'custom', 'n'),
- 'year' => format_date(REQUEST_TIME, 'custom', 'Y'),
- );
- }
-
- $element['#tree'] = TRUE;
+ element_set_attributes($element, array('id', 'name', 'type', 'min', 'max', 'step', 'value', 'size'));
+ _form_set_attributes($element, array('form-' . $element['attribute']['type']));
- // Determine the order of day, month, year in the site's chosen date format.
- $format = variable_get('date_format_short', 'm/d/Y - H:i');
- $sort = array();
- $sort['day'] = max(strpos($format, 'd'), strpos($format, 'j'));
- $sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
- $sort['year'] = strpos($format, 'Y');
- asort($sort);
- $order = array_keys($sort);
-
- // Output multi-selector for date.
- foreach ($order as $type) {
- switch ($type) {
- case 'day':
- $options = drupal_map_assoc(range(1, 31));
- $title = t('Day');
- break;
-
- case 'month':
- $options = drupal_map_assoc(range(1, 12), 'map_month');
- $title = t('Month');
- break;
-
- case 'year':
- $options = drupal_map_assoc(range(1900, 2050));
- $title = t('Year');
- break;
- }
-
- $element[$type] = array(
- '#type' => 'select',
- '#title' => $title,
- '#title_display' => 'invisible',
- '#value' => $element['#value'][$type],
- '#attributes' => $element['#attributes'],
- '#options' => $options,
- );
- }
-
- return $element;
-}
-
-/**
- * Validates the date type to prevent invalid dates (e.g., February 30, 2006).
- */
-function date_validate($element) {
- if (!checkdate($element['#value']['month'], $element['#value']['day'], $element['#value']['year'])) {
- form_error($element, t('The specified date is invalid.'));
- }
-}
-
-/**
- * Renders a month name for display.
- *
- * Callback for drupal_map_assoc() within form_process_date().
- */
-function map_month($month) {
- $months = &drupal_static(__FUNCTION__, array(
- 1 => 'Jan',
- 2 => 'Feb',
- 3 => 'Mar',
- 4 => 'Apr',
- 5 => 'May',
- 6 => 'Jun',
- 7 => 'Jul',
- 8 => 'Aug',
- 9 => 'Sep',
- 10 => 'Oct',
- 11 => 'Nov',
- 12 => 'Dec',
- ));
- return t($months[$month]);
+ return '';
}
/**
diff --git a/core/includes/theme.inc b/core/includes/theme.inc
index ba6baf2..dedb36d 100644
--- a/core/includes/theme.inc
+++ b/core/includes/theme.inc
@@ -1548,6 +1548,7 @@ function template_preprocess_datetime(&$variables) {
$variables['html'] = FALSE;
}
}
+ $variables['attributes'] = new Attribute($variables['attributes']);
}
/**
diff --git a/core/modules/comment/comment.info b/core/modules/comment/comment.info
index 6028bda..ffdf639 100644
--- a/core/modules/comment/comment.info
+++ b/core/modules/comment/comment.info
@@ -4,6 +4,7 @@ package = Core
version = VERSION
core = 8.x
dependencies[] = node
+dependencies[] = datetime
dependencies[] = text
configure = admin/content/comment
stylesheets[all][] = comment.theme.css
diff --git a/core/modules/comment/lib/Drupal/comment/CommentFormController.php b/core/modules/comment/lib/Drupal/comment/CommentFormController.php
index db15889..ea47835 100644
--- a/core/modules/comment/lib/Drupal/comment/CommentFormController.php
+++ b/core/modules/comment/lib/Drupal/comment/CommentFormController.php
@@ -64,7 +64,7 @@ public function form(array $form, array &$form_state, EntityInterface $comment)
if ($is_admin) {
$author = (!$comment->uid && $comment->name ? $comment->name : $comment->registered_name);
$status = (isset($comment->status) ? $comment->status : COMMENT_NOT_PUBLISHED);
- $date = (!empty($comment->date) ? $comment->date : format_date($comment->created, 'custom', 'Y-m-d H:i O'));
+ $date = (!empty($comment->date) ? $comment->date : new DrupalDateTime($comment->created));
}
else {
if ($user->uid) {
@@ -135,10 +135,9 @@ public function form(array $form, array &$form_state, EntityInterface $comment)
// Add administrative comment publishing options.
$form['author']['date'] = array(
- '#type' => 'textfield',
+ '#type' => 'datetime',
'#title' => t('Authored on'),
'#default_value' => $date,
- '#maxlength' => 25,
'#size' => 20,
'#access' => $is_admin,
);
@@ -238,8 +237,8 @@ public function validate(array $form, array &$form_state) {
$account = user_load_by_name($form_state['values']['name']);
$form_state['values']['uid'] = $account ? $account->uid : 0;
- $date = new DrupalDateTime($form_state['values']['date']);
- if ($date->hasErrors()) {
+ $date = $form_state['values']['date'];
+ if ($date instanceOf DrupalDateTime && $date->hasErrors()) {
form_set_error('date', t('You have to specify a valid date.'));
}
if ($form_state['values']['name'] && !$form_state['values']['is_anonymous'] && !$account) {
@@ -271,11 +270,7 @@ public function validate(array $form, array &$form_state) {
public function submit(array $form, array &$form_state) {
$comment = parent::submit($form, $form_state);
- if (empty($comment->date)) {
- $comment->date = 'now';
- }
- $date = new DrupalDateTime($comment->date);
- $comment->created = $date->getTimestamp();
+ $comment->created = !empty($comment->date) && $comment->date instanceOf DrupalDateTime ? $comment->date->getTimestamp() : REQUEST_TIME;
$comment->changed = REQUEST_TIME;
// If the comment was posted by a registered user, assign the author's ID.
diff --git a/core/modules/comment/lib/Drupal/comment/Tests/CommentPreviewTest.php b/core/modules/comment/lib/Drupal/comment/Tests/CommentPreviewTest.php
index 0738076..63c281c 100644
--- a/core/modules/comment/lib/Drupal/comment/Tests/CommentPreviewTest.php
+++ b/core/modules/comment/lib/Drupal/comment/Tests/CommentPreviewTest.php
@@ -7,6 +7,8 @@
namespace Drupal\comment\Tests;
+use Drupal\Core\Datetime\DrupalDateTime;
+
/**
* Tests previewing comments.
*/
@@ -86,13 +88,16 @@ function testCommentEditPreviewSave() {
$this->setCommentSettings('comment_default_mode', COMMENT_MODE_THREADED, 'Comment paging changed.');
$edit = array();
+ $date = new DrupalDateTime('2008-03-02 17:23');
$edit['subject'] = $this->randomName(8);
$edit['comment_body[' . $langcode . '][0][value]'] = $this->randomName(16);
$edit['name'] = $web_user->name;
- $edit['date'] = '2008-03-02 17:23 +0300';
- $raw_date = strtotime($edit['date']);
+ $edit['date[date]'] = $date->format('Y-m-d');
+ $edit['date[time]'] = $date->format('H:i:s');
+ $raw_date = $date->getTimestamp();
$expected_text_date = format_date($raw_date);
- $expected_form_date = format_date($raw_date, 'custom', 'Y-m-d H:i O');
+ $expected_form_date = $date->format('Y-m-d');
+ $expected_form_time = $date->format('H:i:s');
$comment = $this->postComment($this->node, $edit['subject'], $edit['comment_body[' . $langcode . '][0][value]'], TRUE);
$this->drupalPost('comment/' . $comment->id . '/edit', $edit, t('Preview'));
@@ -107,7 +112,8 @@ function testCommentEditPreviewSave() {
$this->assertFieldByName('subject', $edit['subject'], 'Subject field displayed.');
$this->assertFieldByName('comment_body[' . $langcode . '][0][value]', $edit['comment_body[' . $langcode . '][0][value]'], 'Comment field displayed.');
$this->assertFieldByName('name', $edit['name'], 'Author field displayed.');
- $this->assertFieldByName('date', $edit['date'], 'Date field displayed.');
+ $this->assertFieldByName('date[date]', $edit['date[date]'], 'Date field displayed.');
+ $this->assertFieldByName('date[time]', $edit['date[time]'], 'Time field displayed.');
// Check that saving a comment produces a success message.
$this->drupalPost('comment/' . $comment->id . '/edit', $edit, t('Save'));
@@ -118,14 +124,16 @@ function testCommentEditPreviewSave() {
$this->assertFieldByName('subject', $edit['subject'], 'Subject field displayed.');
$this->assertFieldByName('comment_body[' . $langcode . '][0][value]', $edit['comment_body[' . $langcode . '][0][value]'], 'Comment field displayed.');
$this->assertFieldByName('name', $edit['name'], 'Author field displayed.');
- $this->assertFieldByName('date', $expected_form_date, 'Date field displayed.');
+ $this->assertFieldByName('date[date]', $expected_form_date, 'Date field displayed.');
+ $this->assertFieldByName('date[time]', $expected_form_time, 'Time field displayed.');
// Submit the form using the displayed values.
$displayed = array();
$displayed['subject'] = (string) current($this->xpath("//input[@id='edit-subject']/@value"));
$displayed['comment_body[' . $langcode . '][0][value]'] = (string) current($this->xpath("//textarea[@id='edit-comment-body-" . $langcode . "-0-value']"));
$displayed['name'] = (string) current($this->xpath("//input[@id='edit-name']/@value"));
- $displayed['date'] = (string) current($this->xpath("//input[@id='edit-date']/@value"));
+ $displayed['date[date]'] = (string) current($this->xpath("//input[@id='edit-date-date']/@value"));
+ $displayed['date[time]'] = (string) current($this->xpath("//input[@id='edit-date-time']/@value"));
$this->drupalPost('comment/' . $comment->id . '/edit', $displayed, t('Save'));
// Check that the saved comment is still correct.
diff --git a/core/modules/comment/lib/Drupal/comment/Tests/CommentTestBase.php b/core/modules/comment/lib/Drupal/comment/Tests/CommentTestBase.php
index 902dbdd..4abb87c 100644
--- a/core/modules/comment/lib/Drupal/comment/Tests/CommentTestBase.php
+++ b/core/modules/comment/lib/Drupal/comment/Tests/CommentTestBase.php
@@ -20,7 +20,7 @@
*
* @var array
*/
- public static $modules = array('comment', 'node', 'history');
+ public static $modules = array('comment', 'node', 'history', 'datetime');
/**
* An administrative user with permission to configure comment settings.
diff --git a/core/modules/datetime/datetime.info b/core/modules/datetime/datetime.info
new file mode 100644
index 0000000..f1bb32c
--- /dev/null
+++ b/core/modules/datetime/datetime.info
@@ -0,0 +1,6 @@
+name = Datetime
+description = Defines datetime form elements and a datetime field type.
+package = Core
+version = VERSION
+core = 8.x
+dependencies[] = field
diff --git a/core/modules/datetime/datetime.install b/core/modules/datetime/datetime.install
new file mode 100644
index 0000000..8f8513b
--- /dev/null
+++ b/core/modules/datetime/datetime.install
@@ -0,0 +1,35 @@
+ 'The date value',
+ 'type' => 'varchar',
+ 'length' => 20,
+ 'not null' => FALSE,
+ );
+ $indexes = array(
+ 'value' => array('value'),
+ );
+ return array('columns' => $db_columns, 'indexes' => $indexes);
+}
+
+/**
+ * Renames all datetime fields that may have existed prior to D8 for later upgrade by contrib Date module.
+ */
+function datetime_install() {
+ db_update('field_config')
+ ->fields(array(
+ 'type' => 'datetime_old',
+ ))
+ ->condition('type', 'datetime')
+ ->execute();
+}
diff --git a/core/modules/datetime/datetime.module b/core/modules/datetime/datetime.module
new file mode 100644
index 0000000..8195819
--- /dev/null
+++ b/core/modules/datetime/datetime.module
@@ -0,0 +1,651 @@
+ TRUE,
+ '#element_validate' => array('datetime_validate'),
+ '#process' => array('datetime_form_process'),
+ '#theme' => 'datetime_form',
+ '#theme_wrappers' => array('form_element'),
+ '#date_date_format' => variable_get('date_format_html_date', 'Y-m-d'),
+ '#date_date_element' => 'date',
+ '#date_date_callbacks' => array(),
+ '#date_time_format' => variable_get('date_format_html_time', 'H:i:s'),
+ '#date_time_element' => 'time',
+ '#date_time_callbacks' => array(),
+ '#date_year_range' => '1900:2050',
+ '#date_increment' => 1,
+ '#date_timezone' => '',
+ );
+ return $types;
+}
+
+/**
+ * Implements hook_theme().
+ */
+function datetime_theme() {
+ return array(
+ 'datetime_form' => array(
+ 'render element' => 'element',
+ ),
+ );
+}
+
+/**
+ * Implements hook_field_is_empty().
+ */
+function datetime_field_is_empty($item, $field) {
+ if (empty($item['value'])) {
+ return TRUE;
+ }
+ return FALSE;
+}
+
+/**
+ * Implements hook_field_info().
+ */
+function datetime_field_info() {
+ return array(
+ 'datetime' => array(
+ 'label' => 'Date',
+ 'description' => t('Create and store date values.'),
+ 'settings' => array(
+ 'datetime_type' => 'datetime',
+ ),
+ 'instance_settings' => array(
+ 'default_value' => 'now',
+ ),
+ 'default_widget' => 'datetime_default',
+ 'default_formatter' => 'datetime_default',
+ 'default_token_formatter' => 'datetime_plain',
+ 'field item class' => '\Drupal\datetime\Type\DateTimeItem',
+ ),
+ );
+}
+
+/**
+ * Implements hook_field_settings_form().
+ */
+function datetime_field_settings_form($field, $instance, $has_data) {
+ $settings = $field['settings'];
+
+ $form['datetime_type'] = array(
+ '#type' => 'select',
+ '#title' => t('Date type'),
+ '#description' => t('Choose the type of date to create.'),
+ '#default_value' => $settings['datetime_type'],
+ '#options' => array(
+ 'datetime' => t('Date and time'),
+ 'date' => t('Date only'),
+ ),
+ );
+ return $form;
+}
+
+/**
+ * Implements hook_field_instance_settings_form().
+ */
+function datetime_field_instance_settings_form($field, $instance) {
+ $widget = $instance['widget'];
+ $settings = $instance['settings'];
+ $widget_settings = $instance['widget']['settings'];
+
+ $form['default_value'] = array(
+ '#type' => 'select',
+ '#title' => t('Default date'),
+ '#description' => t('Set a default value for this date.'),
+ '#default_value' => $settings['default_value'],
+ '#options' => array('blank' => t('No default value'), 'now' => t('The current date')),
+ '#weight' => 1,
+ );
+
+ return $form;
+}
+
+/**
+ * Validation callback for the datetime widget element.
+ *
+ * The date has already been validated by the datetime form type
+ * validator and transformed to an date object. We just need to
+ * convert the date back to a the storage timezone and format.
+ */
+function datetime_widget_validate(&$element, &$form_state) {
+ if (!form_get_errors()) {
+ $input_exists = FALSE;
+ $input = drupal_array_get_nested_value($form_state['values'], $element['#parents'], $input_exists);
+ if ($input_exists) {
+ // The date should have been returned to a date object at this
+ // point by datetime_validate(), which runs before this.
+ if (!empty($input['value'])) {
+ $date = $input['value'];
+ if ($date instanceOf DrupalDateTime && !$date->hasErrors()) {
+
+ // If this is a date-only field, set it to the default time so
+ // the timezone conversion can be reversed.
+ if ($element['value']['#date_time_element'] == 'none') {
+ datetime_date_default_time($date);
+ }
+ // Adjust the date for storage.
+ $date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));
+ $value = $date->format($element['value']['#date_storage_format']);
+ form_set_value($element['value'], $value, $form_state);
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Implements hook_field_load().
+ *
+ * The function generates a Date object for each field early so that it is
+ * cached in the field cache. This avoids the need to generate the
+ * object later. The date will be retrieved in UTC, the local timezone
+ * adjustment must be made in real time, based on the preferences of the
+ * site and user.
+ */
+function datetime_field_load($entity_type, $entities, $field, $instances, $langcode, &$items) {
+
+ foreach ($entities as $id => $entity) {
+ foreach ($items[$id] as $delta => $item) {
+ $items[$id][$delta]['date'] = NULL;
+ $value = isset($item['value']) ? $item['value'] : NULL;
+ if (!empty($value)) {
+ $storage_format = $field['settings']['datetime_type'] == 'date' ? DATETIME_DATE_STORAGE_FORMAT: DATETIME_DATETIME_STORAGE_FORMAT;
+ $date = new DrupalDateTime($value, DATETIME_STORAGE_TIMEZONE, $storage_format);
+ if ($date instanceOf DrupalDateTime && !$date->hasErrors()) {
+ $items[$id][$delta]['date'] = $date;
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Sets a default value for an empty date field.
+ *
+ * Callback for $instance['default_value_function'], as implemented
+ * by Drupal\datetime\Plugin\field\widget\DateTimeDatepicker.
+ */
+function datetime_default_value($entity_type, $entity, $field, $instance, $langcode) {
+
+ $value = '';
+ $date = '';
+ if ($instance['settings']['default_value'] == 'now') {
+ // A default value should be in the format and timezone used
+ // for date storage.
+ $date = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE);
+ $storage_format = $field['settings']['datetime_type'] == 'date' ? DATETIME_DATE_STORAGE_FORMAT: DATETIME_DATETIME_STORAGE_FORMAT;
+ $value = $date->format($storage_format);
+ }
+
+ // We only provide a default value for the first item, as do
+ // all fields. Otherwise there is no way to clear out unwanted
+ // values on multiple value fields.
+ $item = array();
+ $item[0]['value'] = $value;
+ $item[0]['date'] = $date;
+
+ return $item;
+}
+
+/**
+ * Helper function to set a consistent time on a date without time.
+ *
+ * The default time for a date without time can be anything, so long as
+ * it is consistently applied. If we use noon, dates in most timezones
+ * will have the same value for in both the local timezone and UTC.
+ */
+function datetime_date_default_time($date) {
+ $date->setTime(12, 0, 0);
+}
+
+
+/**
+ * Specifies the start and end year to use as a date range.
+ *
+ * Handles a string like -3:+3 or 2001:2010 to describe a dynamic range of
+ * minimum and maximum years to use in a date selector.
+ *
+ * Centers the range around the current year, if any, but expands it far enough
+ * so it will pick up the year value in the field in case the value in the field
+ * is outside the initial range.
+ *
+ * @param string $string
+ * A min and max year string like '-3:+1' or '2000:2010' or '2000:+3'.
+ * @param object $date
+ * (optional) A date object to test as a default value. Defaults to NULL.
+ *
+ * @return array
+ * A numerically indexed array, containing the minimum and maximum year
+ * described by this pattern.
+ */
+function date_range_years($string, $date = NULL) {
+
+ // We use the full path to the date class to avoid the need to
+ // include this file when not being used.
+ $this_year = date_format(new \Drupal\Core\Datetime\DrupalDateTime(), 'Y');
+ list($min_year, $max_year) = explode(':', $string);
+
+ // Valid patterns would be -5:+5, 0:+1, 2008:2010.
+ $plus_pattern = '@[\+|\-][0-9]{1,4}@';
+ $year_pattern = '@^[0-9]{4}@';
+ if (!preg_match($year_pattern, $min_year, $matches)) {
+ if (preg_match($plus_pattern, $min_year, $matches)) {
+ $min_year = $this_year + $matches[0];
+ }
+ else {
+ $min_year = $this_year;
+ }
+ }
+ if (!preg_match($year_pattern, $max_year, $matches)) {
+ if (preg_match($plus_pattern, $max_year, $matches)) {
+ $max_year = $this_year + $matches[0];
+ }
+ else {
+ $max_year = $this_year;
+ }
+ }
+ // We expect the $min year to be less than the $max year.
+ // Some custom values for -99:+99 might not obey that.
+ if ($min_year > $max_year) {
+ $temp = $max_year;
+ $max_year = $min_year;
+ $min_year = $temp;
+ }
+ // If there is a current value, stretch the range to include it.
+ $value_year = $date instanceOf \Drupal\Core\Datetime\DrupalDateTime ? $date->format('Y') : '';
+ if (!empty($value_year)) {
+ $min_year = min($value_year, $min_year);
+ $max_year = max($value_year, $max_year);
+ }
+ return array($min_year, $max_year);
+}
+
+
+/**
+ * Returns HTML for a HTML5-compatible #datetime form element.
+ *
+ * Wrapper around the date element type which creates a date and a time
+ * component for a date.
+ *
+ * @param array $variables
+ * An associative array containing:
+ * - element: An associative array containing the properties of the element.
+ * Properties used: #title, #value, #options, #description, #required,
+ * #attributes.
+ *
+ * @ingroup themeable
+ * @see form_process_datetime()
+ */
+function theme_datetime_form($variables) {
+
+ $element = $variables['element'];
+
+ $attributes = array();
+ if (isset($element['#id'])) {
+ $attributes['id'] = $element['#id'];
+ }
+ if (!empty($element['#attributes']['class'])) {
+ $attributes['class'] = (array) $element['#attributes']['class'];
+ }
+ $attributes['class'][] = 'container-inline';
+
+ return '
' . drupal_render_children($element) . '
';
+}
+
+/**
+ * Expands a #datetime element type into date and/or time elements.
+ *
+ * All form elements are designed to have sane defaults so any or all can be
+ * omitted. Both the date and time components are configurable so they can be
+ * output as HTML5 datetime elements or not, as desired.
+ *
+ * Examples of possible configurations include:
+ * HTML5 date and time:
+ * #date_date_element = 'date';
+ * #date_time_element = 'time';
+ * HTML5 datetime:
+ * #date_date_element = 'datetime';
+ * #date_time_element = 'none';
+ * HTML5 time only:
+ * #date_date_element = 'none';
+ * #date_time_element = 'time'
+ * Non-HTML5:
+ * #date_date_element = 'text';
+ * #date_time_element = 'text';
+ *
+ * Required settings:
+ * - #default_value: A DrupalDateTime object, adjusted to the proper local
+ * timezone. Converting a date stored in the database from UTC to the local
+ * zone and converting it back to UTC before storing it is not handled here.
+ * This element accepts a date as the default value, and then converts the
+ * user input strings back into a new date object on submission. No timezone
+ * adjustment is performed.
+ * Optional properties include:
+ * - #date_date_format: A date format string that describes the format that
+ * should be displayed to the end user for the date. When using HTML5
+ * elements the format MUST use the appropriate HTML5 format for that
+ * element, no other format will work. See the format_date() function for a
+ * list of the possible formats and HTML5 standards for the HTML5
+ * requirements. Defaults to the right HTML5 format for the chosen element
+ * if a HTML5 element is used, or
+ * variable_get('date_format_html_date', 'Y-m-d').
+ * - #date_date_element: The date element. Options are:
+ * - datetime: Use the HTML5 datetime element type.
+ * - datetime-local: Use the HTML5 datetime-local element type.
+ * - date: Use the HTML5 date element type.
+ * - text: No HTML5 element, use a normal text field.
+ * - none: Do not display a date element.
+ * - #date_date_callbacks: Array of optional callbacks for the date element.
+ * Can be used to add a jQuery datepicker.
+ * - #date_time_element: The time element. Options are:
+ * - time: Use a HTML5 time element type.
+ * - text: No HTML5 element, use a normal text field.
+ * - none: Do not display a time element.
+ * - #date_time_format: A date format string that describes the format that
+ * should be displayed to the end user for the time. When using HTML5
+ * elements the format MUST use the appropriate HTML5 format for that
+ * element, no other format will work. See the format_date() function for
+ * a list of the possible formats and HTML5 standards for the HTML5
+ * requirements. Defaults to the right HTML5 format for the chosen element
+ * if a HTML5 element is used, otherwise defaults to
+ * variable_get('date_format_html_time', 'H:i:s').
+ * - #date_time_callbacks: An array of optional callbacks for the time
+ * element. Can be used to add a jQuery timepicker or an 'All day' checkbox.
+ * - #date_year_range: A description of the range of years to allow, like
+ * '1900:2050', '-3:+3' or '2000:+3', where the first value describes the
+ * earliest year and the second the latest year in the range. A year
+ * in either position means that specific year. A +/- value describes a
+ * dynamic value that is that many years earlier or later than the current
+ * year at the time the form is displayed. Used in jQueryUI datepicker year
+ * range and HTML5 min/max date settings. Defaults to '1900:2050'.
+ * - #date_increment: The increment to use for minutes and seconds, i.e.
+ * '15' would show only :00, :15, :30 and :45. Used for HTML5 step values and
+ * jQueryUI datepicker settings. Defaults to 1 to show every minute.
+ * - #date_timezone: The local timezone to use when creating dates. Generally
+ * this should be left empty and it will be set correctly for the user using
+ * the form. Useful if the default value is empty to designate a desired
+ * timezone for dates created in form processing. If a default date is
+ * provided, this value will be ignored, the timezone in the default date
+ * takes precedence. Defaults to the value returned by
+ * drupal_get_user_timezone().
+ *
+ * Example usage:
+ * @code
+ * $date = new DrupalDateTime('2000-01-01 00:00:00');
+ * $form = array(
+ * '#type' => 'datetime',
+ * '#default_value' => $date,
+ * '#date_date_element' => 'date',
+ * '#date_time_element' => 'none',
+ * '#date_year_range' => '2010:+3',
+ * );
+ * @endcode
+ */
+function datetime_form_process($element, &$form_state) {
+
+ // The value callback has populated the #value array.
+ $date = !empty($element['#value']['object']) ? $element['#value']['object'] : NULL;
+
+ // Set a fallback timezone.
+ if ($date instanceOf DrupalDateTime) {
+ $element['#date_timezone'] = $date->getTimezone()->getName();
+ }
+ elseif (!empty($element['#timezone'])) {
+ $element['#date_timezone'] = $element['#date_timezone'];
+ }
+ else {
+ $element['#date_timezone'] = drupal_get_user_timezone();
+ }
+
+ $element['#tree'] = TRUE;
+
+ if ($element['#date_date_element'] != 'none') {
+
+ $date_format = $element['#date_date_element'] != 'none' ? datetime_html5_format('date', $element) : '';
+ $date_value = !empty($date) ? $date->format($date_format) : $element['#value']['date'];
+
+ // Creating format examples on every individual date item is messy, and
+ // placeholders are invalid for HTML5 date and datetime, so an example
+ // format is appended to the title to appear in tooltips.
+ $extra_attributes = array(
+ 'title' => t('Date (i.e. !format)', array('!format' => datetime_format_example($date_format))),
+ 'type' => $element['#date_date_element'],
+ );
+
+ // Adds the HTML5 date attributes.
+ if ($date instanceOf DrupalDateTime && !$date->hasErrors()) {
+ $html5_min = clone($date);
+ $range = date_range_years($element['#date_year_range'], $date);
+ $html5_min->setDate($range[0], 1, 1)->setTime(0, 0, 0);
+ $html5_max = clone($date);
+ $html5_max->setDate($range[1], 12, 31)->setTime(23, 59, 59);
+
+ $extra_attributes += array(
+ 'min' => $html5_min->format($date_format),
+ 'max' => $html5_max->format($date_format),
+ );
+ }
+
+ $element['date'] = array(
+ '#type' => 'date',
+ '#title' => t('Date'),
+ '#title_display' => 'invisible',
+ '#value' => $date_value,
+ '#attributes' => $element['#attributes'] + $extra_attributes,
+ '#required' => $element['#required'],
+ '#size' => max(12, strlen($element['#value']['date'])),
+ );
+
+ // Allows custom callbacks to alter the element.
+ if (!empty($element['#date_date_callbacks'])) {
+ foreach ($element['#date_date_callbacks'] as $callback) {
+ if (function_exists($callback)) {
+ $callback($element, $form_state, $date);
+ }
+ }
+ }
+ }
+
+ if ($element['#date_time_element'] != 'none') {
+
+ $time_format = $element['#date_time_element'] != 'none' ? datetime_html5_format('time', $element) : '';
+ $time_value = !empty($date) ? $date->format($time_format) : $element['#value']['time'];
+
+ // Adds the HTML5 attributes.
+ $extra_attributes = array(
+ 'title' =>t('Time (i.e. !format)', array('!format' => datetime_format_example($time_format))),
+ 'type' => $element['#date_time_element'],
+ 'step' => ($element['#date_increment'] * 60),
+ );
+ $element['time'] = array(
+ '#type' => 'date',
+ '#title' => t('Time'),
+ '#title_display' => 'invisible',
+ '#value' => $time_value,
+ '#attributes' => $element['#attributes'] + $extra_attributes,
+ '#required' => $element['#required'],
+ '#size' => 12,
+ );
+
+ // Allows custom callbacks to alter the element.
+ if (!empty($element['#date_time_callbacks'])) {
+ foreach ($element['#date_time_callbacks'] as $callback) {
+ if (function_exists($callback)) {
+ $callback($element, $form_state, $date);
+ }
+ }
+ }
+ }
+
+ return $element;
+}
+
+/**
+ * Value callback for a datetime_form element.
+ *
+ * @param array $element
+ * The form element whose value is being populated.
+ * @param array $input
+ * The incoming input to populate the form element. If this is FALSE, the
+ * element's default value should be returned.
+ *
+ * @return array
+ * The data that will appear in the $element_state['values'] collection for
+ * this element. Return nothing to use the default.
+ */
+function form_type_datetime_value($element, $input = FALSE) {
+ if ($input !== FALSE) {
+ $date_input = $element['#date_date_element'] != 'none' && !empty($input['date']) ? $input['date'] : '';
+ $time_input = $element['#date_time_element'] != 'none' && !empty($input['time']) ? $input['time'] : '';
+ $date_format = $element['#date_date_element'] != 'none' ? datetime_html5_format('date', $element['#date_date_format']) : '';
+ $time_format = $element['#date_time_element'] != 'none' ? datetime_html5_format('time', $element['#date_time_format']) : '';
+ $timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL;
+ $date = new DrupalDateTime(trim($date_input . ' ' . $time_input), $timezone, trim($date_format . ' ' . $time_format));
+ $input = array(
+ 'date' => $date_input,
+ 'time' => $time_input,
+ 'object' => $date instanceOf DrupalDateTime && !$date->hasErrors() ? $date : NULL,
+ );
+ }
+ else {
+ $date = $element['#default_value'];
+ if ($date instanceOf DrupalDateTime && !$date->hasErrors()) {
+ $input = array(
+ 'date' => $date->format($element['#date_date_format']),
+ 'time' => $date->format($element['#date_time_format']),
+ 'object' => $date,
+ );
+ }
+ else {
+ $input = array(
+ 'date' => '',
+ 'time' => '',
+ 'object' => NULL,
+ );
+ }
+ }
+ return $input;
+}
+
+/**
+ * Validates the date and sets errors.
+ *
+ * If the date is valid, the date object created from the user input is set in
+ * the form for use by the caller.
+ */
+function datetime_validate($element, &$form_state) {
+
+ $input_exists = FALSE;
+ $input = drupal_array_get_nested_value($form_state['values'], $element['#parents'], $input_exists);
+ if ($input_exists) {
+
+ $title = !empty($element['#title']) ? $element['#title'] : '';
+ $date_format = $element['#date_date_element'] != 'none' ? datetime_html5_format('date', $element) : '';
+ $time_format = $element['#date_time_element'] != 'none' ? datetime_html5_format('time', $element) : '';
+ $format = trim($date_format . ' ' . $time_format);
+
+ // If there's empty input and the field is not required, set it to empty.
+ if (empty($input['date']) && empty($input['time']) && !$element['#required']) {
+ form_set_value($element, NULL, $form_state);
+ }
+ // If there's empty input and the field is required, set an error. A
+ // reminder of the required format in the message provides a good UX.
+ elseif (empty($input['date']) && empty($input['time']) && $element['#required']) {
+ form_error($element, t('The %field date is required. Please enter a date in the format %format.', array('%field' => $title, '%format' => datetime_format_example($format))));
+ }
+ else {
+ // If there's a date with no errors, set the value.
+ $date_input = $element['#date_date_element'] != 'none' && !empty($input['date']) ? $input['date'] : '';
+ $time_input = $element['#date_time_element'] != 'none' && !empty($input['time']) ? $input['time'] : '';
+ $date = new DrupalDateTime(trim($date_input . ' ' . $time_input), $element['#date_timezone'], $format);
+ if ($date instanceOf DrupalDateTime && !$date->hasErrors()) {
+ form_set_value($element, $date, $form_state);
+ }
+ // If the input is invalid, set an error. A reminder of the required
+ // format in the message provides a good UX.
+ else {
+ form_error($element, t('The %field date is invalid. Please enter a date in the format %format.', array('%field' => $title, '%format' => datetime_format_example($format))));
+ }
+ }
+ }
+}
+
+/**
+ * Retrieves the right format for a HTML5 date element.
+ *
+ * The format is important because these elements will not work with any other
+ * format.
+ *
+ * @param string $part
+ * The type of element format to retrieve.
+ * @param string $element
+ * The $element to assess.
+ *
+ * @return string
+ * Returns the right format for the type of element, or the original format
+ * if this is not a HTML5 element.
+ */
+function datetime_html5_format($part, $element) {
+ switch ($part) {
+ case 'date':
+ switch ($element['#date_date_element']) {
+ case 'date':
+ return variable_get('date_format_html_date', 'Y-m-d');
+ case 'datetime':
+ case 'datetime-local':
+ return variable_get('date_format_html_datetime', 'Y-m-d\TH:i:sO');
+ default:
+ return $element['#date_date_format'];
+ }
+ break;
+ case 'time':
+ switch ($element['#date_time_element']) {
+ case 'time':
+ return variable_get('date_format_html_time', 'H:i:s');
+ default:
+ return $element['#date_time_format'];
+ }
+ break;
+ }
+}
+
+/**
+ * Creates an example for a date format.
+ *
+ * This is centralized for a consistent method of creating these examples.
+ */
+function datetime_format_example($format) {
+ $date = &drupal_static(__FUNCTION__);
+ if (empty($date)) {
+ $date = new DrupalDateTime();
+ }
+ return $date->format($format);
+}
diff --git a/core/modules/datetime/datetime.views.inc b/core/modules/datetime/datetime.views.inc
new file mode 100644
index 0000000..b3292f2
--- /dev/null
+++ b/core/modules/datetime/datetime.views.inc
@@ -0,0 +1,31 @@
+ $item) {
+
+ $formatted_date = '';
+ $iso_date = '';
+
+ if (!empty($item['date'])) {
+ // The date was created and verified during field_load(), so
+ // it's safe to use without further inspection.
+ $date = $item['date'];
+
+ // Create the ISO date in Universal Time.
+ $iso_date = $date->format("Y-m-d\TH:i:s") . 'Z';
+
+ // The formatted output will be in local time.
+ $date->setTimeZone(timezone_open(drupal_get_user_timezone()));
+ if ($this->field['settings']['datetime_type'] == 'date') {
+ // A date without time will pick up the current time,
+ // use the default.
+ datetime_date_default_time($date);
+ }
+ $formatted_date = $this->dateFormat($date);
+ }
+
+ // Display the date using theme datetime.
+ // @TODO How should RDFa attributes be added to this?
+ $elements[$delta] = array(
+ '#theme' => 'datetime',
+ '#text' => $formatted_date,
+ '#html' => FALSE,
+ '#attributes' => array(
+ 'datetime' => $iso_date,
+ 'property' => array('dc:date'),
+ 'datatype' => 'xsd:dateTime',
+ ),
+ );
+ }
+
+ return $elements;
+
+ }
+
+ /**
+ * Output a formatted date value.
+ *
+ * @param object $date
+ * A date object.
+ *
+ * @return string
+ * A formatted date string using the chosen format.
+ */
+ function dateFormat($date) {
+ $format_type = $this->getSetting('format_type');
+ return format_date($date->getTimestamp(), $format_type);
+ }
+
+ /**
+ * Implements \Drupal\field\Plugin\Type\Formatter\FormatterInterface::settingsForm().
+ */
+ public function settingsForm(array $form, array &$form_state) {
+
+ $element = array();
+
+ $time = new DrupalDateTime();
+ $format_types = system_get_date_types();
+ if (!empty($format_types)) {
+ foreach ($format_types as $type => $type_info) {
+ $options[$type] = $type_info['title'] . ' (' . format_date($time->format('U'), $type) . ')';
+ }
+ }
+
+ $elements['format_type'] = array(
+ '#type' => 'select',
+ '#title' => t('Date format'),
+ '#description' => t("Choose a format for displaying the date. Be sure to set a format appropriate for the field, i.e. omitting time for a field that only has a date."),
+ '#options' => $options,
+ '#default_value' => $this->getSetting('format_type'),
+ );
+
+ return $elements;
+ }
+
+ /**
+ * Implements \Drupal\field\Plugin\Type\Formatter\FormatterInterface::settingsSummary().
+ */
+ public function settingsSummary() {
+
+ $date = new DrupalDateTime();
+ $output = array();
+ $output[] = t('Format: @display', array('@display' => $this->dateFormat($date, FALSE)));
+ return implode(' ', $output);
+
+ }
+}
diff --git a/core/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimePlainFormatter.php b/core/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimePlainFormatter.php
new file mode 100644
index 0000000..2c08dcf
--- /dev/null
+++ b/core/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimePlainFormatter.php
@@ -0,0 +1,59 @@
+ $item) {
+
+ $output = '';
+ if (!empty($item['date'])) {
+ // The date was created and verified during field_load(), so
+ // it's safe to use without further inspection.
+ $date = $item['date'];
+ $date->setTimeZone(timezone_open(drupal_get_user_timezone()));
+ $format = DATETIME_DATETIME_STORAGE_FORMAT;
+ if ($this->field['settings']['datetime_type'] == 'date') {
+ // A date without time will pick up the current time,
+ // use the default.
+ datetime_date_default_time($date);
+ $format = DATETIME_DATE_STORAGE_FORMAT;
+ }
+ $output = $date->format($format);
+ }
+ $elements[$delta] = array('#markup' => $output);
+ }
+
+ return $elements;
+ }
+}
diff --git a/core/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDefaultWidget.php b/core/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDefaultWidget.php
new file mode 100644
index 0000000..aa61842
--- /dev/null
+++ b/core/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDefaultWidget.php
@@ -0,0 +1,131 @@
+field;
+ $instance = $this->instance;
+
+ // We're nesting some sub-elements inside the parent, so we
+ // need a wrapper. We also need to add another #title attribute
+ // at the top level for ease in identifying this item in error
+ // messages. We don't want to display this title because the
+ // actual title display is handled at a higher level by the Field
+ // module.
+
+ $element['#theme_wrappers'][] = 'form_element';
+ $element['#attributes']['class'][] = 'container-inline';
+ $element['#element_validate'][] = 'datetime_widget_validate';
+
+ // Identify the type of date and time elements to use.
+ switch ($field['settings']['datetime_type']) {
+ case 'date':
+ $date_type = 'date';
+ $time_type = 'none';
+ $date_format = variable_get('date_format_html_date', 'Y-m-d');
+ $time_format = '';
+ $element_format = $date_format;
+ $storage_format = DATETIME_DATE_STORAGE_FORMAT;
+ break;
+ default:
+ $date_type = 'date';
+ $time_type = 'time';
+ $date_format = variable_get('date_format_html_date', 'Y-m-d');
+ $time_format = variable_get('date_format_html_time', 'H:i:s');
+ $element_format = $date_format . ' ' . $time_format;
+ $storage_format = DATETIME_DATETIME_STORAGE_FORMAT;
+ break;
+ }
+
+ $element['value'] = array(
+ '#type' => 'datetime',
+ '#default_value' => NULL,
+ '#title' => $instance->definition['label'],
+ '#title_display' => 'invisible',
+ '#date_increment' => 1,
+ '#date_date_format'=> $date_format,
+ '#date_date_element' => $date_type,
+ '#date_date_callbacks' => array(),
+ '#date_time_format' => $time_format,
+ '#date_time_element' => $time_type,
+ '#date_time_callbacks' => array(),
+ '#date_timezone' => drupal_get_user_timezone(),
+ '#required' => $element['#required'],
+ );
+
+ // Set the storage and widget options so the validation can use them.
+ // The validator won't have access to field or instance settings.
+ $element['value']['#date_element_format'] = $element_format;
+ $element['value']['#date_storage_format'] = $storage_format;
+
+ if (!empty($items[$delta]['date'])) {
+ $date = $items[$delta]['date'];
+ // The date was created and verified during field_load(), so
+ // it's safe to use without further inspection.
+ $date->setTimezone( new \DateTimeZone($element['value']['#date_timezone']));
+ if ($field['settings']['datetime_type'] == 'date') {
+ // A date without time will pick up the current time,
+ // use the default time.
+ datetime_date_default_time($date);
+ }
+ $element['value']['#default_value'] = $date;
+ }
+
+ return $element;
+ }
+
+}
diff --git a/core/modules/datetime/lib/Drupal/datetime/Tests/DateTimeFieldTest.php b/core/modules/datetime/lib/Drupal/datetime/Tests/DateTimeFieldTest.php
new file mode 100644
index 0000000..d158776
--- /dev/null
+++ b/core/modules/datetime/lib/Drupal/datetime/Tests/DateTimeFieldTest.php
@@ -0,0 +1,345 @@
+ 'Datetime Field',
+ 'description' => 'Tests datetime field functionality.',
+ 'group' => 'Datetime',
+ );
+ }
+
+ function setUp() {
+ parent::setUp();
+
+ $this->web_user = $this->drupalCreateUser(array(
+ 'access field_test content',
+ 'administer field_test content',
+ 'administer content types',
+ ));
+ $this->drupalLogin($this->web_user);
+
+ // Create a field with settings to validate.
+ $this->field = array(
+ 'field_name' => drupal_strtolower($this->randomName()),
+ 'type' => 'datetime',
+ 'settings' => array('datetime_type' => 'date'),
+ );
+ field_create_field($this->field);
+ $this->instance = array(
+ 'field_name' => $this->field['field_name'],
+ 'entity_type' => 'test_entity',
+ 'bundle' => 'test_bundle',
+ 'widget' => array(
+ 'type' => 'datetime_default',
+ ),
+ 'settings' => array(
+ 'default_value' => 'blank',
+ ),
+ 'display' => array(
+ 'full' => array(
+ 'type' => 'datetime_default',
+ 'label' => 'hidden',
+ 'settings' => array('format_type' => 'medium'),
+ ),
+ ),
+ );
+ field_create_instance($this->instance);
+
+ }
+
+ /**
+ * Tests date field.
+ */
+ function testDateField() {
+
+ // Display creation form.
+ $this->drupalGet('test-entity/add/test_bundle');
+ $langcode = LANGUAGE_NOT_SPECIFIED;
+ $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][date]", '', 'Date element found.');
+ $this->assertNoFieldByName("{$this->field['field_name']}[$langcode][0][value][time]", '', 'Time element not found.');
+
+ // Submit a valid date and ensure it is accepted.
+ $value = '2012-12-31 00:00:00';
+ $date = new DrupalDateTime($value);
+ $date_format = variable_get('date_format_html_date', 'Y-m-d');
+ $time_format = variable_get('date_format_html_time', 'H:i:s');
+
+ $edit = array(
+ "{$this->field['field_name']}[$langcode][0][value][date]" => $date->format($date_format),
+ );
+ $this->drupalPost(NULL, $edit, t('Save'));
+ preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
+ $id = $match[1];
+ $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)));
+ $this->assertRaw($date->format($date_format));
+ $this->assertNoRaw($date->format($time_format));
+
+ // The expected values will use the default time.
+ datetime_date_default_time($date);
+
+ // Verify that the date is output according to the formatter settings.
+ $options = array(
+ 'format_type' => array('short', 'medium', 'long'),
+ );
+ foreach ($options as $setting => $values) {
+ foreach ($values as $new_value) {
+ // Update the field formatter settings.
+ $this->instance['display']['full']['settings'] = array($setting => $new_value);
+ field_update_instance($this->instance);
+
+ $this->renderTestEntity($id);
+ switch ($setting) {
+ case 'format_type':
+ // Verify that a date is displayed.
+ $expected = format_date($date->getTimestamp(), $new_value);
+ $this->renderTestEntity($id);
+ $this->assertText($expected, "Formatted date field using $new_value format displayed as $expected.");
+ break;
+ }
+ }
+ }
+
+ // Verify that the plain formatter works.
+ $this->instance['display']['full']['type'] = 'datetime_plain';
+ field_update_instance($this->instance);
+ $expected = $date->format(DATETIME_DATE_STORAGE_FORMAT);
+ $this->renderTestEntity($id);
+ $this->assertText($expected, "Formatted date field using plain format displayed as $expected.");
+
+ }
+
+ /**
+ * Tests date and time field.
+ */
+ function testDatetimeField() {
+
+ // Change the field to a datetime field.
+ $this->field['settings']['datetime_type'] = 'datetime';
+ field_update_field($this->field);
+
+ // Display creation form.
+ $this->drupalGet('test-entity/add/test_bundle');
+ $langcode = LANGUAGE_NOT_SPECIFIED;
+ $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][date]", '', 'Date element found.');
+ $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][time]", '', 'Time element found.');
+
+ // Submit a valid date and ensure it is accepted.
+ $value = '2012-12-31 00:00:00';
+ $date = new DrupalDateTime($value);
+ $date_format = variable_get('date_format_html_date', 'Y-m-d');
+ $time_format = variable_get('date_format_html_time', 'H:i:s');
+
+ $edit = array(
+ "{$this->field['field_name']}[$langcode][0][value][date]" => $date->format($date_format),
+ "{$this->field['field_name']}[$langcode][0][value][time]" => $date->format($time_format),
+ );
+ $this->drupalPost(NULL, $edit, t('Save'));
+ preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
+ $id = $match[1];
+ $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)));
+ $this->assertRaw($date->format($date_format));
+ $this->assertRaw($date->format($time_format));
+
+ // Verify that the date is output according to the formatter settings.
+ $options = array(
+ 'format_type' => array('short', 'medium', 'long'),
+ );
+ foreach ($options as $setting => $values) {
+ foreach ($values as $new_value) {
+ // Update the field formatter settings.
+ $this->instance['display']['full']['settings'] = array($setting => $new_value);
+ field_update_instance($this->instance);
+
+ $this->renderTestEntity($id);
+ switch ($setting) {
+ case 'format_type':
+ // Verify that a date is displayed.
+ $expected = format_date($date->getTimestamp(), $new_value);
+ $this->renderTestEntity($id);
+ $this->assertText($expected, "Formatted datetime field using $new_value format displayed as $expected.");
+ break;
+ }
+ }
+ }
+
+ // Verify that the plain formatter works.
+ $this->instance['display']['full']['type'] = 'datetime_plain';
+ field_update_instance($this->instance);
+ $expected = $date->format(DATETIME_DATETIME_STORAGE_FORMAT);
+ $this->renderTestEntity($id);
+ $this->assertText($expected, "Formatted datetime field using plain format displayed as $expected.");
+
+ }
+
+ /**
+ * Test default values.
+ */
+ function testDefaultValue() {
+
+ // Change the field to a datetime field.
+ $this->field['settings']['datetime_type'] = 'datetime';
+ field_update_field($this->field);
+
+ // Set the default value to 'now'.
+ $this->instance['settings']['default_value'] = 'now';
+ field_update_instance($this->instance);
+
+ // Display creation form.
+ $date = new DrupalDateTime();
+ $date_format = 'Y-m-d';
+ $this->drupalGet('test-entity/add/test_bundle');
+ $langcode = LANGUAGE_NOT_SPECIFIED;
+
+ // See if current date is set.
+ // We can't test for the precise time because it may be a few seconds between
+ // the time the comparison date is created and the form date, so we just
+ // test the date and that the time is not empty.
+ $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][date]", $date->format($date_format), 'Date element found.');
+ $this->assertNoFieldByName("{$this->field['field_name']}[$langcode][0][value][time]", '', 'Time element found.');
+
+ // Set the default value to 'blank'.
+ $this->instance['settings']['default_value'] = 'blank';
+ field_update_instance($this->instance);
+
+ // Display creation form.
+ $date = new DrupalDateTime();
+ $this->drupalGet('test-entity/add/test_bundle');
+
+ // See that no date is set.
+ $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][date]", '', 'Date element found.');
+ $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][time]", '', 'Time element found.');
+
+ }
+
+ /**
+ * Test that invalid values are caught and marked as invalid.
+ */
+ function testInvalidField() {
+
+ // Change the field to a datetime field.
+ $this->field['settings']['datetime_type'] = 'datetime';
+ field_update_field($this->field);
+
+ // Display creation form.
+ $this->drupalGet('test-entity/add/test_bundle');
+ $langcode = LANGUAGE_NOT_SPECIFIED;
+ $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][date]", '', 'Date element found.');
+ $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][time]", '', 'Time element found.');
+
+ // Submit invalid dates and ensure they is not accepted.
+ $date_value = '';
+ $edit = array(
+ "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value,
+ "{$this->field['field_name']}[$langcode][0][value][time]" => '12:00:00',
+ );
+ $this->drupalPost(NULL, $edit, t('Save'));
+ $this->assertText('date is invalid', "Empty date value has been caught.");
+
+ $date_value = 'aaaa-12-01';
+ $edit = array(
+ "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value,
+ "{$this->field['field_name']}[$langcode][0][value][time]" => '00:00:00',
+ );
+ $this->drupalPost(NULL, $edit, t('Save'));
+ $this->assertText('date is invalid', "Invalid year value $date_value has been caught.");
+
+ $date_value = '2012-75-01';
+ $edit = array(
+ "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value,
+ "{$this->field['field_name']}[$langcode][0][value][time]" => '00:00:00',
+ );
+ $this->drupalPost(NULL, $edit, t('Save'));
+ $this->assertText('date is invalid', "Invalid month value $date_value has been caught.");
+
+ $date_value = '2012-12-99';
+ $edit = array(
+ "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value,
+ "{$this->field['field_name']}[$langcode][0][value][time]" => '00:00:00',
+ );
+ $this->drupalPost(NULL, $edit, t('Save'));
+ $this->assertText('date is invalid', "Invalid day value $date_value has been caught.");
+
+ $date_value = '2012-12-01';
+ $time_value = '';
+ $edit = array(
+ "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value,
+ "{$this->field['field_name']}[$langcode][0][value][time]" => $time_value,
+ );
+ $this->drupalPost(NULL, $edit, t('Save'));
+ $this->assertText('date is invalid', "Empty time value has been caught.");
+
+ $date_value = '2012-12-01';
+ $time_value = '49:00:00';
+ $edit = array(
+ "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value,
+ "{$this->field['field_name']}[$langcode][0][value][time]" => $time_value,
+ );
+ $this->drupalPost(NULL, $edit, t('Save'));
+ $this->assertText('date is invalid', "Invalid hour value $time_value has been caught.");
+
+ $date_value = '2012-12-01';
+ $time_value = '12:99:00';
+ $edit = array(
+ "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value,
+ "{$this->field['field_name']}[$langcode][0][value][time]" => $time_value,
+ );
+ $this->drupalPost(NULL, $edit, t('Save'));
+ $this->assertText('date is invalid', "Invalid minute value $time_value has been caught.");
+
+ $date_value = '2012-12-01';
+ $time_value = '12:15:99';
+ $edit = array(
+ "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value,
+ "{$this->field['field_name']}[$langcode][0][value][time]" => $time_value,
+ );
+ $this->drupalPost(NULL, $edit, t('Save'));
+ $this->assertText('date is invalid', "Invalid second value $time_value has been caught.");
+
+ }
+
+ /**
+ * Renders a test_entity and sets the output in the internal browser.
+ *
+ * @param int $id
+ * The test_entity ID to render.
+ * @param string $view_mode
+ * (optional) The view mode to use for rendering.
+ * @param bool $reset
+ * (optional) Whether to reset the test_entity controller cache. Defaults to
+ * TRUE to simplify testing.
+ */
+ protected function renderTestEntity($id, $view_mode = 'full', $reset = TRUE) {
+ if ($reset) {
+ entity_get_controller('test_entity')->resetCache(array($id));
+ }
+ $entity = field_test_entity_test_load($id);
+ field_attach_prepare_view('test_entity', array($entity->id() => $entity), $view_mode);
+ $entity->content = field_attach_view('test_entity', $entity, $view_mode);
+
+ $output = drupal_render($entity->content);
+ $this->drupalSetContent($output);
+ $this->verbose($output);
+ }
+}
diff --git a/core/modules/datetime/lib/Drupal/datetime/Type/DateTimeItem.php b/core/modules/datetime/lib/Drupal/datetime/Type/DateTimeItem.php
new file mode 100644
index 0000000..2d14e5a
--- /dev/null
+++ b/core/modules/datetime/lib/Drupal/datetime/Type/DateTimeItem.php
@@ -0,0 +1,39 @@
+ 'date',
+ 'label' => t('Date value'),
+ );
+ }
+ return self::$propertyDefinitions;
+ }
+}
diff --git a/core/modules/forum/lib/Drupal/forum/Tests/ForumBlockTest.php b/core/modules/forum/lib/Drupal/forum/Tests/ForumBlockTest.php
index e121cb8..7c5655d 100644
--- a/core/modules/forum/lib/Drupal/forum/Tests/ForumBlockTest.php
+++ b/core/modules/forum/lib/Drupal/forum/Tests/ForumBlockTest.php
@@ -8,6 +8,7 @@
namespace Drupal\forum\Tests;
use Drupal\simpletest\WebTestBase;
+use Drupal\Core\Datetime\DrupalDateTime;
/**
* Provides automated tests for the Forum blocks.
@@ -103,16 +104,17 @@ function testActiveForumTopicsBlock() {
$topics = $this->createForumTopics(10);
// Comment on the first 5 topics.
- $timestamp = time();
+ $date = new DrupalDateTime();
$langcode = LANGUAGE_NOT_SPECIFIED;
for ($index = 0; $index < 5; $index++) {
// Get the node from the topic title.
$node = $this->drupalGetNodeByTitle($topics[$index]);
+ $date->modify('+1 minute');
$comment = entity_create('comment', array(
'nid' => $node->nid,
'subject' => $this->randomString(20),
'comment_body' => array(LANGUAGE_NOT_SPECIFIED => $this->randomString(256)),
- 'created' => $timestamp + $index,
+ 'created' => $date->getTimestamp(),
));
comment_save($comment);
}
@@ -171,20 +173,23 @@ function testActiveForumTopicsBlock() {
*/
private function createForumTopics($count = 5) {
$topics = array();
- $timestamp = time() - 24 * 60 * 60;
+ $date = new DrupalDateTime();
+ $date->modify('-24 hours');
for ($index = 0; $index < $count; $index++) {
// Generate a random subject/body.
$title = $this->randomName(20);
$body = $this->randomName(200);
+ // Forum posts are ordered by timestamp, so force a unique timestamp by
+ // changing the date.
+ $date->modify('+1 minute');
$langcode = LANGUAGE_NOT_SPECIFIED;
$edit = array(
'title' => $title,
"body[$langcode][0][value]" => $body,
- // Forum posts are ordered by timestamp, so force a unique timestamp by
- // adding the index.
- 'date' => date('c', $timestamp + $index),
+ 'date[date]' => $date->format('Y-m-d'),
+ 'date[time]' => $date->format('H:i:s'),
);
// Create the forum topic, preselecting the forum ID via a URL parameter.
diff --git a/core/modules/node/lib/Drupal/node/NodeFormController.php b/core/modules/node/lib/Drupal/node/NodeFormController.php
index 43456c7..871cb1b 100644
--- a/core/modules/node/lib/Drupal/node/NodeFormController.php
+++ b/core/modules/node/lib/Drupal/node/NodeFormController.php
@@ -40,7 +40,7 @@ protected function prepareEntity(EntityInterface $node) {
$node->created = REQUEST_TIME;
}
else {
- $node->date = format_date($node->created, 'custom', 'Y-m-d H:i:s O');
+ $node->date = new DrupalDateTime($node->created);
// Remove the log message from the original node entity.
$node->log = NULL;
}
@@ -190,12 +190,11 @@ public function form(array $form, array &$form_state, EntityInterface $node) {
'#weight' => -1,
'#description' => t('Leave blank for %anonymous.', array('%anonymous' => $user_config->get('anonymous'))),
);
-
+ $format = variable_get('date_format_html_date', 'Y-m-d') . ' ' . variable_get('date_format_html_time', 'H:i:s');
$form['author']['date'] = array(
- '#type' => 'textfield',
+ '#type' => 'datetime',
'#title' => t('Authored on'),
- '#maxlength' => 25,
- '#description' => t('Format: %time. The date format is YYYY-MM-DD and %timezone is the time zone offset from UTC. Leave blank to use the time of form submission.', array('%time' => !empty($node->date) ? date_format(date_create($node->date), 'Y-m-d H:i:s O') : format_date($node->created, 'custom', 'Y-m-d H:i:s O'), '%timezone' => !empty($node->date) ? date_format(date_create($node->date), 'O') : format_date($node->created, 'custom', 'O'))),
+ '#description' => t('Format: %format. Leave blank to use the time of form submission.', array('%format' => datetime_format_example($format))),
'#default_value' => !empty($node->date) ? $node->date : '',
);
@@ -289,8 +288,8 @@ public function validate(array $form, array &$form_state) {
}
// Validate the "authored on" field.
- $date = new DrupalDateTime($node->date);
- if ($date->hasErrors()) {
+ // The date element contains the date object.
+ if ($node->date instanceOf DrupalDateTime && $node->date->hasErrors()) {
form_set_error('date', t('You have to specify a valid date.'));
}
diff --git a/core/modules/node/lib/Drupal/node/Tests/NodeTestBase.php b/core/modules/node/lib/Drupal/node/Tests/NodeTestBase.php
index 1bba558..f1ed6aa 100644
--- a/core/modules/node/lib/Drupal/node/Tests/NodeTestBase.php
+++ b/core/modules/node/lib/Drupal/node/Tests/NodeTestBase.php
@@ -19,7 +19,7 @@
*
* @var array
*/
- public static $modules = array('node');
+ public static $modules = array('node', 'datetime');
function setUp() {
parent::setUp();
diff --git a/core/modules/node/node.info b/core/modules/node/node.info
index da33c43..e8413a2 100644
--- a/core/modules/node/node.info
+++ b/core/modules/node/node.info
@@ -3,4 +3,5 @@ description = Allows content to be submitted to the site and displayed on pages.
package = Core
version = VERSION
core = 8.x
+dependencies[] = datetime
configure = admin/structure/types
diff --git a/core/modules/node/node.module b/core/modules/node/node.module
index bdfae92..dbed2b6 100644
--- a/core/modules/node/node.module
+++ b/core/modules/node/node.module
@@ -973,14 +973,7 @@ function node_submit(Node $node) {
$node->revision_uid = $user->uid;
}
- if (!empty($node->date)) {
- $node_created = new DrupalDateTime($node->date);
- $node->created = $node_created->getTimestamp();
- }
- else {
- $node->created = REQUEST_TIME;
- }
-
+ $node->created = !empty($node->date) && $node->date instanceOf DrupalDateTime ? $node->date->getTimestamp() : REQUEST_TIME;
$node->validated = TRUE;
return $node;
diff --git a/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php b/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php
index 001e521..0c92360 100644
--- a/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php
+++ b/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php
@@ -15,6 +15,7 @@
use DOMDocument;
use DOMXPath;
use SimpleXMLElement;
+use Drupal\Core\Datetime\DrupalDateTime;
/**
* Test case for typical Drupal tests.
@@ -1199,7 +1200,6 @@ protected function drupalPost($path, $edit, $submit, array $options = array(), a
// handleForm() function, it's not currently a requirement.
$submit_matches = TRUE;
}
-
// We post only if we managed to handle every field in edit and the
// submit button matches.
if (!$edit && ($submit_matches || !isset($submit))) {
@@ -1535,6 +1535,10 @@ protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
case 'password':
case 'email':
case 'search':
+ case 'date':
+ case 'time':
+ case 'datetime':
+ case 'datetime-local';
$post[$name] = $edit[$name];
unset($edit[$name]);
break;
diff --git a/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php b/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php
index 9efe0c3..c0f4722 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php
@@ -16,7 +16,7 @@ class FormTest extends WebTestBase {
*
* @var array
*/
- public static $modules = array('form_test', 'file');
+ public static $modules = array('form_test', 'file', 'datetime');
public static function getInfo() {
return array(
@@ -510,7 +510,7 @@ function testDisabledElements() {
// All the elements should be marked as disabled, including the ones below
// the disabled container.
- $this->assertEqual(count($disabled_elements), 40, 'The correct elements have the disabled property in the HTML code.');
+ $this->assertEqual(count($disabled_elements), 39, 'The correct elements have the disabled property in the HTML code.');
$this->drupalPost(NULL, $edit, t('Submit'));
$returned_values['hijacked'] = drupal_json_decode($this->content);
@@ -560,7 +560,7 @@ function testDisabledMarkup() {
'textarea' => 'textarea',
'select' => 'select',
'weight' => 'select',
- 'date' => 'select',
+ 'datetime' => 'datetime',
);
foreach ($form as $name => $item) {
diff --git a/core/modules/system/lib/Drupal/system/Tests/TypedData/TypedDataTest.php b/core/modules/system/lib/Drupal/system/Tests/TypedData/TypedDataTest.php
index 00e4c95..66a4272 100644
--- a/core/modules/system/lib/Drupal/system/Tests/TypedData/TypedDataTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/TypedData/TypedDataTest.php
@@ -72,7 +72,7 @@ public function testGetAndSet() {
$this->assertNull($wrapper->getValue(), 'Float wrapper is null-able.');
// Date type.
- $value = new DrupalDateTime(REQUEST_TIME);
+ $value = new DrupalDateTime();
$wrapper = $this->createTypedData(array('type' => 'date'), $value);
$this->assertTrue($wrapper->getValue() === $value, 'Date value was fetched.');
$new_value = REQUEST_TIME + 1;
diff --git a/core/modules/system/system.module b/core/modules/system/system.module
index e837fe9..527eca3 100644
--- a/core/modules/system/system.module
+++ b/core/modules/system/system.module
@@ -480,8 +480,6 @@ function system_element_info() {
);
$types['date'] = array(
'#input' => TRUE,
- '#element_validate' => array('date_validate'),
- '#process' => array('form_process_date'),
'#theme' => 'date',
'#theme_wrappers' => array('form_element'),
);
diff --git a/core/modules/system/tests/modules/form_test/form_test.module b/core/modules/system/tests/modules/form_test/form_test.module
index 1801809..e245325 100644
--- a/core/modules/system/tests/modules/form_test/form_test.module
+++ b/core/modules/system/tests/modules/form_test/form_test.module
@@ -6,6 +6,7 @@
*/
use Drupal\form_test\Callbacks;
+use Drupal\Core\Datetime\DrupalDateTime;
/**
* Implements hook_menu().
@@ -1727,23 +1728,6 @@ function _form_test_disabled_elements($form, &$form_state) {
'#disabled' => TRUE,
);
- // Date.
- $form['date'] = array(
- '#type' => 'date',
- '#title' => 'date',
- '#disabled' => TRUE,
- '#default_value' => array(
- 'day' => 19,
- 'month' => 11,
- 'year' => 1978,
- ),
- '#test_hijack_value' => array(
- 'day' => 20,
- 'month' => 12,
- 'year' => 1979,
- ),
- );
-
// The #disabled state should propagate to children.
$form['disabled_container'] = array(
'#disabled' => TRUE,
@@ -1757,6 +1741,19 @@ function _form_test_disabled_elements($form, &$form_state) {
);
}
+ // Date.
+ $date = new DrupalDateTime('1978-11-01 10:30:00', 'Europe/Berlin');
+ $expected = array('date' => '1978-11-01 10:30:00', 'timezone_type' => 3, 'timezone' => 'Europe/Berlin',);
+ $form['disabled_container']['disabled_container_datetime'] = array(
+ '#type' => 'datetime',
+ '#title' => 'datetime',
+ '#default_value' => $date,
+ '#expected_value' => $expected,
+ '#test_hijack_value' => new DrupalDateTime('1978-12-02 11:30:00', 'Europe/Berlin'),
+ '#date_timezone' => 'Europe/Berlin',
+ );
+
+
// Try to hijack the email field with a valid email.
$form['disabled_container']['disabled_container_email'] = array(
'#type' => 'email',
diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/LegacyTest.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/LegacyTest.php
index d00f373..d4f7be5 100644
--- a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/LegacyTest.php
+++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/LegacyTest.php
@@ -7,6 +7,8 @@
namespace Drupal\taxonomy\Tests;
+use Drupal\Core\Datetime\DrupalDateTime;
+
/**
* Test for legacy node bug.
*/
@@ -34,14 +36,16 @@ function setUp() {
function testTaxonomyLegacyNode() {
// Posts an article with a taxonomy term and a date prior to 1970.
$langcode = LANGUAGE_NOT_SPECIFIED;
+ $date = new DrupalDateTime('1969-01-01 00:00:00');
$edit = array();
$edit['title'] = $this->randomName();
- $edit['date'] = '1969-01-01 00:00:00 -0500';
+ $edit['date[date]'] = $date->format('Y-m-d');
+ $edit['date[time]'] = $date->format('H:i:s');
$edit["body[$langcode][0][value]"] = $this->randomName();
$edit["field_tags[$langcode]"] = $this->randomName();
$this->drupalPost('node/add/article', $edit, t('Save'));
// Checks that the node has been saved.
$node = $this->drupalGetNodeByTitle($edit['title']);
- $this->assertEqual($node->created, strtotime($edit['date']), 'Legacy node was saved with the right date.');
+ $this->assertEqual($node->created, $date->getTimestamp(), 'Legacy node was saved with the right date.');
}
}